I guess for the python experts this is a simple one... but maybe someone can explain me.
imagine we have two classes with the same field:
class A:
name = 'a'
class B:
name = 'b'
and now we got a third class that inherits both:
class C(A, B):
...
now we can check for the name-field with C.name
, I found out, that the fields value is 'a'
.
Can I assume that it's always the first class that "wins"? Shouldn't the second class overwrite the first ones fields?
In Python, when a class inherits from multiple parent classes, the order of inheritance determines the resolution order for attribute lookup. In the case of class C inheriting from classes A and B, the attribute lookup follows a specific order called the Method Resolution Order (MRO).
The MRO determines the sequence in which Python looks for attributes in the parent classes. It uses a depth-first, left-to-right algorithm known as the C3 linearization. In this algorithm, the first parent class listed in the inheritance declaration has higher priority.
In your example, since class A is listed before class B in the inheritance declaration of class C (class C(A, B)
), the attribute lookup for name
will find it in class A first. If class A did not define the name
attribute, then it would be looked up in class B.
If you were to reverse the order of inheritance (class C(B, A)
), the attribute lookup for name
would find it in class B first. In that case, class B would "win" and overwrite the value defined in class A.
To see the MRO of a class, you can use the built-in __mro__
attribute or the mro()
method. For example, C.__mro__
will give you the MRO tuple for class C, which represents the order of attribute lookup.
Keep in mind that the MRO and attribute lookup behavior may change in different versions of Python or with different class hierarchies, so it's always a good practice to be explicit and avoid relying on the order of inheritance for attribute resolution.