Tuesday, 10 September 2013

Understanding python's super method, Why D().test() will return 'B->C' and not 'B-->A'

Understanding python's super method, Why D().test() will return 'B->C' and
not 'B-->A'

I have looked at other question here regarding python's super() method but
I am still finding it difficult to understand the whole concept.
I am also looking at the example in the book pro python
The example referenced there is
class A(object):
def test(self):
return 'A'
class B(A):
def test(self):
return 'B-->' + super(B, self).test()
class C(A):
def test(self):
return 'C'
class D(B, C):
pass
>>> A().test()
'A'
>>> B().test()
'B-->A'
>>> C().test()
'C'
>>> D().test()
'B-->C'
>>> A.__mro__
(__main__.A, object)
>>> B.__mro__
(__main__.B, __main__.A, object)
>>> C.__mro__
(__main__.C, __main__.A, object)
>>> D.__mro__
(__main__.D, __main__.B, __main__.C, __main__.A, object)
Why doing D().test() we get the output as 'B-->C' instead of 'B-->A'
The explanation in the book is
In the most common case, which includes the usage shown here, super()
takes two arguments: a class and an instance of that class. As our example
here has shown, the instance object determines which MRO will be used to
resolve any attributes on the resulting object. The provided class
determines a subset of that MRO, because super() only uses those entries
in the MRO that occur after the class provided.
I still find the explanation a bit difficult to understand. This might be
a possible duplicate and questions similar to this has been asked many
times, but if I get an understanding of this I might be able to understand
the rest of other questions better.
Understanding Python super() and init methods
How to use 'super' in Python?
python, inheritance, super() method
[python]: confused by super()

No comments:

Post a Comment