[Python] How to tell Python to re-evaluate a parent class method's interface? [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    Over the years, I can't count how many times I wanted to do something like this in Python:

    class A:
    DEFAULT_MESSAGE = "Unspecified Country"

    def do_it(message=DEFAULT_MESSAGE):
    print(message)

    class B(A):
    DEFAULT_MESSAGE = "Mexico"


    And have this result in:

    > A().do_it()
    Unspecified Country
    > B().do_it()
    Mexico


    Without having to redefine the method:

    class B(A):
    DEFAULT_MESSAGE = "Mexico"

    def do_it(message=DEFAULT_MESSAGE):
    super().do_it(message)


    Or do an arguably bad design pattern of setting the default message to None for the method, and instead reading the DEFAULT_MESSAGE in the implementation of the method.

    Is there a better, more DRY design-pattern that helps with this? Or is there some way to tell Python to re-evaluate the interfaces on parent class methods when defining a new, sub-class?

    Continue reading...

Compartilhe esta Página