user32882
user32882

Reputation: 5877

subclasses with functions having the same name in python

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?

Upvotes: 0

Views: 1187

Answers (1)

chepner
chepner

Reputation: 531075

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.

Upvotes: 5

Related Questions