简体   繁体   English

Python从一个类继承但是覆盖方法调用另一个类?

[英]Python Inherit from one class but override method calling another class?

Let say I have 3 classes: A, B and C. A is a base class for B and B is for C. Hierarchy is kept normally here, but for one method it should be different. 假设我有3个类:A,B和C.A是B的基类,B是C语言。层次结构在这里保持正常,但对于一种方法,它应该是不同的。 For C class it should act like it was inherited from A. 对于C类,它应该像从A继承的那样行事。

For example like this: 例如这样:

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'

So basically it should work like this: 所以基本上它应该像这样工作:

a = A()
a.m()
a

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

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

But it is not going to work for C class, because I get this error: 但它不适用于C类,因为我收到此错误:

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

To solve this for C class I could inherit from class A, but I want to inherit everything from B and for that specific method m call super for base class A. I mean that method is one exception. 为了解决这个为C级,我可以从A类继承,但我想继承一切从B和针对具体方法m调用超为基类A.我的意思是方法是一个例外。 Or should I call it somehow differently for class C in order to work? 或者我应该以不同的方式为C类调用它以便工作?

How can I do that? 我怎样才能做到这一点?

There are in fact two ways to solve this: you can shortcut the call to super() and totally bypass the mro as in Mathias Ettinger's answer, or you can just issue the correct call to super() : 事实上有两种方法可以解决这个问题:您可以将调用快捷方式设置为super()并完全绕过mro,就像Mathias Ettinger的答案一样,或者您可以发出正确的调用super()

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

Remember that super() expects as first argument the class from which it should start looking up the mro. 请记住, super()期望从第一个参数开始查找mro的类。 It's usually the class in which the call is made, but you can pass another class upper in the mro if you want. 它通常是进行调用的类,但如果需要,可以在mro中传递另一个类。

Using the super call, python will inspect the MRO of your class to determine which class to use when calling the function you want. 使用super调用,python将检查你的类的MRO ,以确定在调用你想要的函数时使用哪个类。

Since you want to short-circuit this behaviour, you can explicitly state the class you want to use the method from with: 由于您希望使此行为短路,因此您可以使用以下方法明确声明要使用该方法的类:

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

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

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