How does Python's super() work with multiple inheritance? -
i'm pretty new in python object oriented programming , have trouble understanding super() function (new style classes) when comes multiple inheritance.
for example if have like:
class first(object): def __init__(self): print "first" class second(object): def __init__(self): print "second" class third(first, second): def __init__(self): super(third, self).__init__() print "that's it" what don't is: third() class inherit both constructor methods? if yes, 1 run super() , why?
and if want run other one? know has python method resolution order (mro).
this detailed reasonable amount of detail guido himself @ http://python-history.blogspot.com/2010/06/method-resolution-order.html (including 2 earlier attempts).
in example, third() call first.__init__. python looks each attribute in class's parents listed left right. in case looking __init__. so, if define
class third(first, second): ... python start looking @ first, and, if first doesn't have attribute, @ second.
this situation becomes more complex when inheritance starts crossing paths (for example if first inherited second). read link above more details, but, in nutshell, python try maintain order in each class appears on inheritance list, starting child class itself.
so, instance, if had:
class first(object): def __init__(self): print "first" class second(first): def __init__(self): print "second" class third(first): def __init__(self): print "third" class fourth(second, third): def __init__(self): super(fourth, self).__init__() print "that's it" the mro [fourth, second, third, first].
by way: if python cannot find coherent method resolution order, it'll raise exception, instead of falling behaviour might surprise user.
edited add example of ambiguous mro:
class first(object): def __init__(self): print "first" class second(first): def __init__(self): print "second" class third(first, second): def __init__(self): print "third" should third's mro [first, second] or [second, first]? there's no obvious expectation, , python raise error:
typeerror: error when calling metaclass bases cannot create consistent method resolution order (mro) bases second, first
[edit] see several people arguing examples above lack super() calls, let me explain: point of examples show how mro constructed. not intended print "first\nsecond\third" or whatever. can - , should, of course, play around example, add super() calls, see happens, , gain deeper understanding of python's inheritance model. goal here keep simple , show how mro build. , built explained:
>>> fourth.__mro__ (<class '__main__.fourth'>, <class '__main__.second'>, <class '__main__.third'>, <class '__main__.first'>, <type 'object'>)
Comments
Post a Comment