Search code examples
pythonoopmultiple-inheritance

Call method of base class from derived class object python


I have two class and methods having same name .I have the object of derived class. When i call the method (foo) from derived class object it should call the base class method.

class A:
    def foo(self):
        print "A Foo"

class B(A):
    def foo(self):
        print "B Foo"

b = B()
b.foo() # "B Foo"

After doing some search i got some solution as below and not sure whether it is proper way of doing it or not

a = A()
b.__class__.__bases__[0].foo(a) # A Foo

Is there any better way of doing it.


Solution

  • If you're using Python 3, use super:

    class A:
        def talk(self):
            print('Hi from A-land!')
    
    class B(A):
        def talk(self):
            print('Hello from B-land!')
    
        def pass_message(self):
            super().talk()
    
    b = B()
    b.talk()
    b.pass_message()
    

    Output:

    Hello from B-land!
    Hi from A-land!
    

    You can do the same thing in Python 2 if you inherit from object and specify the parameters of super:

    class B(A):
        def talk(self):
            print('Hello from B-land!')
    
        def pass_message(self):
            super(B, self).talk()
    
    b = B()
    b.talk()
    b.pass_message()
    

    Output:

    Hello from B-land!
    Hi from A-land!
    

    You can also call the method as if it were a free function:

    A.talk(b)
    B.talk(b)  # the same as b.talk()
    

    Output:

    Hi from A-land!
    Hello from B-land!