Python 从一个 class 继承但覆盖调用另一个 class 的方法?

Python Inherit from one class but override method calling another class?

假设我有 3 个 classes:A、B 和 C。A 是 B 的基础 class,B 是 C 的基础。这里通常保留层次结构,但对于一种方法它应该是不同的。对于 C class,它应该像从 A.

继承的一样

例如像这样:

class A(object):
    def m(self):
        print 'a'

class B(A):
    def m(self):
        super(B, self).m()
        print 'b'

class C(B):
    def m(self):
        super(A, self).m()
        print 'c'

所以基本上它应该像这样工作:

a = A()
a.m()
a

b = B()
b.m()
a
b

c = C()
c.m()
a
c

但它不适用于 C class,因为我收到此错误:

AttributeError: 'super' object has no attribute 'm'

要为 C class 解决此问题,我可以从 class A 继承,但我想从 B 继承所有内容,并且对于该特定方法 m 调用 super for base class A. 我的意思是那个方法是一个例外。或者我应该以某种不同的方式为 class C 调用它才能工作吗?

我该怎么做?

使用 super 调用,python 将检查 class 的 MRO 以确定在调用所需函数时使用哪个 class .

既然你想短路这个行为,你可以明确地声明class你想使用的方法来自:

class C(B):
    def m(self):
        A.m(self)
        print 'c'

实际上有两种方法可以解决这个问题:您可以将调用快捷方式 super() 并像 Mathias Ettinger 的回答那样完全绕过 mro,或者您可以只发出 correct 调用 super():

class C(B):
    def m(self):
        super(B, self).m()
        print 'c'

请记住,super() 期望 class 作为第一个参数,它应该从中开始查找 mro。通常是调用的 class,但如果需要,您可以在 mro 中传递另一个 class 上层。