[Python] How to avoid redefining default parameter with Python inheritance

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

  1. Stack

    Stack Membro Participativo

    For simple inheritance such as

    class Base:
    def __init__(self, env: str = 'prod'):
    #...

    class Derived(Base):
    def __init__(self, env: str = 'prod'):
    super().__init__(str)


    How do I avoid redefining default constructor parameters in both classes? If I instantiate Derived() I do want env to default to 'prod', I just don't want to redefine the value in multiple classes. If I later decide that the default value should be something else (e.g. 'dev'), then I would have to change all derived constructors.

    I was thinking of something like

    class Base:
    def __init__(self, env: str = 'prod'):
    #...

    class Derived(Base):
    def __init__(self, env: str = None):
    if env is None:
    super().__init__()
    else:
    super().__init__(env)


    or maybe defining the default value as a global constant in the base class? Either method seems overly complex. What's the Pythonic way?

    Continue reading...

Compartilhe esta Página