If I write same method in two class how interpreter decides which one to execute.
class A:
method1():
pass
class B:
method1():
class C(A,B):
The class C is inherites both class A and B How do I call Method1() of B class.
If I write same method in two class how interpreter decides which one to execute.
class A:
method1():
pass
class B:
method1():
class C(A,B):
The class C is inherites both class A and B How do I call Method1() of B class.
It takes the first instance
class A:
def method(self):
print ("a")
class B:
def method(self):
print ("b")
class C(A,B):
pass
result
>>> a = C()
>>> a.method()
a
If we see the Method Resolution Order(MRO) for class C, we see the following:
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
.
Since A is mentioned first during the statement class C(A,B):
, the preference for A is higher than B when there is an ambiguity.
To simply call the method1 from class B, we need to reverse the order mentioned in the class C declaration to this:
class C(B,A):
Now the MRO is changed to if we are checking like this - C.mro()
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]