简体   繁体   English

从派生类对象python调用基类的方法

[英]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. 当我从派生类对象调用方法(foo)时,应调用基类方法。

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 : 如果您使用的是Python 3,请使用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 : 如果从object继承并指定super的参数,则可以在Python 2中执行相同的操作:

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. 当您从派生类对象调用方法(foo)时,它不会调用基类方法,因为您将其覆盖 You can use another method name for your base class or derived class to solve the interference. 您可以为基类或派生类使用另一个方法名称来解决干扰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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