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

Call method of base class from derived class object python

我有两个 class 和同名的方法。我有派生的对象 class。当我从派生 class 对象调用方法 (foo) 时,它应该调用基础 class 方法。

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

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

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

经过一番搜索后,我得到了如下解决方案,但不确定这样做是否正确

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

有没有更好的方法呢

如果您使用 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()

输出:

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

你可以在Python2中做同样的事情,如果你继承object并指定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()

输出:

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

您也可以像调用免费函数一样调用该方法:

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

输出:

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

当您从派生的 class 对象调用方法 (foo) 时,它不会调用基础 class 方法,因为您正在 覆盖 它。您可以使用其他方法名称为您的基础 class 或派生 class 来解决干扰。