python - Difference of calling inherited methods in subclass? -


for python 2.5 , later, new style class, what's difference of following code snippets invoking inherited methods in subclass?

class a(object):     def foo(self):         pass  class b(a):     def __init__(self):         self.foo()  class c(a):     def __init__(self):         super(c, self).foo() 

as long dealing single inheritance classes example gave, there not difference. in either case, python uses method resolution order(mro), (which can examine printing c.__mro__) find out first occurance of method foo. these both resolve base class, a's, foo implementation.

however, things become interesting when have multiple inheritance. @ following example:

class w(object):   def foo(self):       print "w"  class x(w):   def foo(self):     #super(x,self).foo()     w.foo(self)     print "x"          class y(w):   def foo(self):     print "y"   class z(x,y):   def __init__(self):     self.foo()  z.__mro__ z = z() 

if @ class x, can either use super invoke base class x, or can use direct call base class w. difference is, when super used, python doesn't specific implementation, rather first implementation in current mro list. mro list z is:

(z,x,y,w)

therefore, 1 using super print: y x

while 1 directly calls base print: w x

basically, using super dynamically invokes first found implementation in mro, while class.foo (or in case self.foo) invokes particular method.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -