0

I am new to python programming, below is the example of parent,child classes,There are two direct super classes (i.e. bases) of C: A and B. A comes before B, so one would naturally think that the super class of C is A. However, A inherits its attribute a from T with value a=0: if super(C,c) was returning the superclass of C, then super(C,c).a would return 0 but its won't?

Could you please help me to understand why its returning 2.why not 0

>>> class T(object):
...     a = 0
>>> class A(T):
...     pass
>>> class B(T):
...     a = 2
>>> class C(A,B):
...     pass
>>> c = C()
>>>super(C,c).a
2

Thanks, Hema

user1559873
  • 6,650
  • 8
  • 25
  • 28

1 Answers1

0

It has to do with Python method resolution order, or MRO. The precise definition of Python's MRO is here: Python 2.3's MRO doc. Edit: this explanation by Guido seems easier to read, and it includes an example exactly like yours.

If you call __mro__ on a class, you'll see the order in which it looks up stuff. In this case:

>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.T'>, <type 'object'>)

So there you can see that it goes to B first, and only then to T. The reason is that it would otherwise be impossible to override attributes from T in B in this structure, and that's unlikely to be the desired behaviour.

Personally I just always avoid this diamond-style inheritance pattern, except of course for object which is the base class of every other class.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79