简体   繁体   中英

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.

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!

When you call the method (foo) from derived class object, it won't call the base class method, because you're overriding it. You can use another method name for your base class or derived class to solve the interference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM