Python Inherit one class, but override a method that calls another class?

Say I have 3 classes: A, B, and C. A is the base class for B and B for C. The hierarchy is supported here, but for one method, it must be different. For class C, it must act as if it was inherited from A.

For example, for example:

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 this should work as follows:

 a = A() am() a b = B() bm() a b c = C() cm() a c 

But it will not work for class C, because I get this error:

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

To solve this for class C, I could inherit from class A, but I want to inherit everything from B and for this particular method m call super for base class A. I mean that this method is one of the exceptions. Or should I somehow call it for class C to work?

How can i do this?

+5
source share
2 answers

Using super call, python will check the MRO of your class to determine which class to use when calling the function you want.

Since you want to shorten this behavior, you can explicitly specify the class with which you want to use the method with:

 class C(B): def m(self): Am(self) print 'c' 
+4
source

There are actually two ways to solve this problem: you can shorten the call to super() and completely bypass mro, as in Matthias Oettinger's answer, or you can simply issue the correct super() call:

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

Remember that super() expects as the first argument to the class from which it should start looking for mro. This is usually the class in which the call is made, but if you want, you can pass another class to mro.

+8
source

Source: https://habr.com/ru/post/1232018/


All Articles