Python Multiple Inheritance Qustion
Solution 1:
I understand calling b.stop() shows "stop A stop!" because b does not override stop() so will inherit stop() from A.
But I do not understand why calling d.stop() only show stop of A,C,D, not ACBD, isn't MRO: D->B->C->A?
B inherits stop
from A, but what that means is that when you try to access B.stop
or some_B_instance.stop
, the attribute search will find the method through A.__dict__
after looking in B.__dict__
. It doesn't put the method in the B
class directly.
When super
follows the MRO of a D instance, class B comes after D, but super
is only interested in looking at B itself at this point, not B's ancestors. It looks in B.__dict__
for a stop
entry, without considering inherited methods; inherited methods will be handled later in the search, when super
reaches the classes those methods are inherited from.
Since inheriting methods doesn't actually put them in B.__dict__
, super
doesn't find stop
in B
.
Solution 2:
B
does not have its own stop
(you'll notice the string "stop B stop"
never appears in the code), so it will never be executed. In other worse, since there is no line of code which could possibly print "stop B stop", it will not be printed.
Post a Comment for "Python Multiple Inheritance Qustion"