1

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Vikas Satpute
  • 174
  • 2
  • 19
  • Please clarify. The title of this post asks one question but the question inside the post asks something slightly different. By asking the second question you seem to know that the MRO says that instances of class C will have their `method1` call A's version. So do you know that for certain and just want help accessing the B version of the method? (Also you forgot the `self` parameters BTW.) – Ray Toal Mar 12 '18 at 06:57
  • Duplicate question its already answered at https://stackoverflow.com/questions/3810410/python-multiple-inheritance-from-different-paths-with-same-method-name – Sateesh Telaprolu Mar 12 '18 at 06:58
  • It's my mistake but still I wan't to call class b method1() how do i call it – Vikas Satpute Mar 12 '18 at 07:45
  • If you are want to call Method1() from B class, just change the order of inheritance in class C like this `class C(B,A):` @VikasSatpute – Debashis Oct 16 '21 at 06:02

2 Answers2

2

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
Samuel Muiruri
  • 492
  • 1
  • 8
  • 17
1

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'>]

Dharman
  • 30,962
  • 25
  • 85
  • 135
Debashis
  • 81
  • 1
  • 9