[Python] Why make cls a position-only argument in __init_subclass__?

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    The docs for the __init_subclass__ hook (see PEP-0487 for background) give this example:

    class Philosopher:
    def __init_subclass__(cls, /, default_name, **kwargs):
    super().__init_subclass__(**kwargs)
    cls.default_name = default_name

    class AustralianPhilosopher(Philosopher, default_name="Bruce"):
    pass


    The / in the method signature threw me for a loop (difficult to search for secondary uses of operators) but I finally ran across the concept of positional-only parameters.

    Why is it used here, in __init_subclass__? Does this mean that all class methods with cls or self as initial arguments should be using /? I thought Python had a "we're-all-adults-here" philosophy where class designers don't have to be bulletproof against malicious use.

    Continue reading...

Compartilhe esta Página