I try to understand in more detail how the super class works, seemingly partially understood, but suddenly I fell for one of the examples that got me into a dead end. Here is the actual example:

class A(object): @classmethod def say_hello(cls): print 'A says hello' class B(A): @classmethod def say_hello(cls): super(B, cls).say_hello() print 'B says hello' class C(A): @classmethod def say_hello(cls): super(C, cls).say_hello() print 'C says hello' class D(B, C): @classmethod def say_hello(cls): super(D, cls).say_hello() print 'D says hello' D.say_hello() 

result:

 A says hello C says hello B says hello D says hello 

I understand that the construction super (D, cls) .say_hello () leads us to the class B method, but something is confused why it then leads to class C, in class B we get super ((class 'B'), (D object )) and this leads us to C. Someone can explain this behavior to me?

  • one
  • Thanks vadim vaduxa, really helped me figure it out, added print (cls .__ mro__) and explained everything at once, since we are in one mro from there and the result is Chp

2 answers 2

To understand, read how multiple inheritance is implemented in python and understand the concepts of "rhomboid inheritance" and "C3-linearization".

It’s best to start with this article: https://ru.wikipedia.org/wiki/%D0%A0%D0%BE%D0%BC%D0%B1%D0%BE%D0%B2%D0%B8%D0% B4% D0% BD% D0% BE% D0% B5_% D0% BD% D0% B0% D1% 81% D0% BB% D0% B5% D0% B4% D0% BE% D0% B2% D0% B0% D0% BD% D0% B8% D0% B5

Read the general part, and then only the item about python in the “Solution” section.

  • I think this answer can be considered partly correct and he really helped me figure it out, but I repeat partially. I think for complete loyalty it was necessary to mention of course about print (cls .__ mro__) in each method of all four classes, from which it follows that we are in the same sequence: ((class ' main .D', class ' main .B', class ' main .C', class ' main .A', class 'object')) inheritance and super (B, cls), take the next class following B, and this is S. All the same, thank you very much. credit for the answer !!! - Chp

D inherits both classes - B and C From class B there will be no transition to C , only to А And from class С - only on А Then, in order to preserve the hierarchy, the first А absorbed by the second.