class - Python super method and calling alternatives -
i see everywhere examples super-class methods should called by:
super(superclass, instance).method(args) is there disadvantage doing:
superclass.method(instance, args)
consider following situation:
class a(object): def __init__(self): print('running a.__init__') super(a,self).__init__() class b(a): def __init__(self): print('running b.__init__') # super(b,self).__init__() a.__init__(self) class c(a): def __init__(self): print('running c.__init__') super(c,self).__init__() class d(b,c): def __init__(self): print('running d.__init__') super(d,self).__init__() foo=d() so classes form so-called inheritance diamond:
/ \ b c \ / d running code yields
running d.__init__ running b.__init__ running a.__init__ that's bad because c's __init__ skipped. reason because b's __init__ calls a's __init__ directly.
the purpose of super resolve inheritance diamonds. if un-comment
# super(b,self).__init__() and comment-out
a.__init__(self) the code yields more desireable result:
running d.__init__ running b.__init__ running c.__init__ running a.__init__ now __init__ methods called. notice @ time define b.__init__ might think super(b,self).__init__() same calling a.__init__(self), you'd wrong. in above situation, super(b,self).__init__() calls c.__init__(self).
holy smokes, b knows nothing c, , yet super(b,self) knows call c's __init__? reason because self.__class__.mro() contains c. in other words, self (or in above, foo) knows c.
so careful -- 2 not fungible. can yield vastly different results.
using super has pitfalls. takes considerable level of coordination between classes in inheritance diagram. (they must, example, either have same call signature __init__, since particular __init__ not know other __init__ super might call next, or else use **kwargs.) furthermore, must consistent using super everywhere. skip once (as in above example) , defeat entire purpose of super. see link more pitfalls.
if have full control on class hierarchy, or avoid inheritance diamonds, there no need super.
very helpful! Here you will get all kind of solution like D-link Router Support
ReplyDelete