0

I have two base classes A and B each of them have a method myfunc, which prints out a different character.

class A:
    def myfunc(self):
        print('A')

class B:
    def myfunc(self):
        print('B')

I have one more class C which is inheriting from A and B both. In class C I have overridden myfunc and called super over it.

class C(B, A):
    def myfunc(self):
        super().myfunc()

Now if I execute following code, it prints only one character

x = C()
x.myfunc()

Output:

B

I tried print(C.__mro__) which gives me (<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>) So it should go to class A and print character A also. right?

Also if I switch the order of inheritance like C(A,B) it and use the same code , it is skipping class B.

My questions:

  1. Why it's skipping class A?
  2. How to execute myfunc method in both classes A and B

I looked up similar discussion but found it confusing.

Jorge Morgado
  • 1,148
  • 7
  • 23
Ajay Verma
  • 610
  • 2
  • 12

1 Answers1

1

Answering question 1:

It is skipping myFunc on class A because what python does when you call super.myFunc() is search for the first function with name myFunc in all the base classes (in this case B and A) and it does that in order, so it first look for myFunc in class B. So, because there is a function named myFunc in class B python stop searching and executes only that.

Answering question 2:

There is a trivial way of doing that which is this:

class A:
    def f(self):
        print('A')

class B:
    def f(self):
        print('B')

class C(B, A):
    def f(self):
        A.f(self)
        B.f(self)

c = C()
c.f()

Basically you can call any function of any class and then pass the instance as the first argument (self). I believe you can't execute both functions with only one call, you will need to make a call for each one.

Jorge Morgado
  • 1,148
  • 7
  • 23