Reputation: 172
In the example below, I've got 2 parent classes who initialize/declare the same variable. Why does it take the first class and not the second class? This is just for knowledge purposes.
class ParentClass:
one = 'I am the first variable'
two = 'I am the second variable'
three = 'I am the thirt variable'
class ParentClass2:
three = 'I am the third variable'
class ChildClass(ParentClass, ParentClass2):
two = 'Different Text'
pass
childObject = ChildClass()
parentObject = ParentClass()
print(parentObject.one)
print(parentObject.two)
print(childObject.one)
print(childObject.two)
print(childObject.three)
Output:
I am the first variable
I am the second variable
I am the first variable
Different Text
I am the thirt variable
Upvotes: 1
Views: 127
Reputation: 180482
Because because ParentClass
comes first in the mro
print(ChildClass.__mro__)
(<class '__main__.ChildClass'>, <class '__main__.ParentClass'>, <class '__main__.ParentClass2'>, <class 'object'>)
If you changed the order you would get the output you expect:
class ChildClass(ParentClass2,ParentClass):
(<class '__main__.ChildClass'>, <class '__main__.ParentClass2'>, <class '__main__.ParentClass'>, <class 'object'>)
Python checks from left to right for the attribute so because you have ParentClass
first you get the attribute from the ParentClass
class
Upvotes: 3