0

I have two classes in python, and a third which inherits from the first two:

class A():
    def __init__(var1, var2):
        self.var1 = var1
        self.var2 = var2
    def MyFunc():
        #do stuff
class B():
   def __init__(var1):
        self.var1 = var1
    def MyFunc():
        #do other stuff

class C(A,B):
    def __init__(self, var1, var2, var3)
        A.__init__(self,var1, var2)
        B.__init__(self, var3)

As you might notice both classes have different functions bearing the same name. Doing the following:

>>> classC = C(1,2,3)
>>> classC.MyFunc()

Appears to work but I would like to be sure of which MyFunc function I am calling. How do I control which function from my subclasses is being called?

user32882
  • 5,094
  • 5
  • 43
  • 82
  • 1
    Related? https://stackoverflow.com/questions/31232098/how-to-call-super-method/31232226 – rayryeng Mar 16 '18 at 14:10
  • `super` is often, but not necessarily always, the correct way to handle multiple inheritance. – chepner Mar 16 '18 at 14:25
  • In particular, correct use of `super` requires a single class that *doesn't* call `super().MyFunc`, and all other classes implementing `MyFunc` need to subclass (directly or transitively) that class and be sure to use `super().MyFunc` in their own implementation. – chepner Mar 16 '18 at 15:20

1 Answers1

5

Attributes not defined by C are searched for using C's method resolution order:

>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

Since C.MyFunc isn't defined, classC.MyFunc resolves to A.MyFunc. B.MyFunc is never called, unless A.MyFunc were to call it explicitly for some reason.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Ok this partly answers the question, but then how can I control which of the two is called? I have a feeling I'm not setting up class `C` correctly... – user32882 Mar 16 '18 at 14:58
  • That depends: which do you *want* to be called? If `A.MyFunc`, do nothing; that already happens. If `B.MyFunc` or both, you need to define `C.MyFunc` to make the appropriate calls. – chepner Mar 16 '18 at 15:03
  • I want to have control at the level of `C` regarding which function I call, without defining new functions in `C` – user32882 Mar 16 '18 at 15:06
  • Meaning when I'm inside of C how do I control which function is called – user32882 Mar 16 '18 at 15:16
  • You explicitly call the one you want, which has to be done from inside `C.MyFunc`. (You could swap the order of `A` and `B` in the parent class list, but that makes *all* methods of one class or another take precedence. If there are any exceptions, you still have to hard-code `C.whatever` to call the non-default one.) – chepner Mar 16 '18 at 15:18