Uncategorized

Unexpected method call order in Python multiple inheritance


I have a child class named USA and it has two parent classes, A and B.
Both parents have a method named change_to_4 and in B.__init__ I call the method, but instead of using the method that I defined in B it uses the A definition of the change_to_4 method.

class A:
    def __init__(self) -> None:
        self.a = 1
        super().__init__()

    def change_to_4(self):
        self.x = 4


class B:
    def __init__(self) -> None:
        self.b = 2
        self.change_to_4()
        super().__init__()

    def change_to_4(self):
        self.b = 4


class USA(A, B):
    def __init__(self) -> None:
        super().__init__()


print(f"A vars = {vars(A())}")
print(f"B vars = {vars(B())}")
print(f"USA vars = {vars(USA())}")

print(f"USA mro -> {USA.__mro__}")

I expect something like this:

A vars = {'a': 1}
B vars = {'b': 4}
USA vars = {'a': 1, 'b': 4}
USA mro -> (<class '__main__.USA'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

But the output is

A vars = {'a': 1}
B vars = {'b': 4}
USA vars = {'a': 1, 'b': 2, 'x': 4}
USA mro -> (<class '__main__.USA'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *