python - Base class method calling the Derived class method when using super. Very confused -
this seems confusing me. explain why unknown magical things happening ?
class a(object): def testa(self): print "testa of a" self.testb() def testb(self): print "testb of a" class b(a): def testa(self): super(b, self).testa() print "testa of b" self.testb() def testb(self): print "testb of b" if __name__ == '__main__': test = b() test.testa()
program output: =============== testa of testb of b --> why calling derived class method ? testa of b testb of b expected output: ================ testa of testb of -- want see here. testa of b testb of b
your answer appreciated. thank you.
in a.testa
, call self.testb
. means call "leaf" definition of testb
current instance. since self
instance of testb
, calls b.testb
.
even though wrote self.testb
inside method defined on class a
, not mean call version of method defined on class a
. calling method on instance, , @ runtime class of instance determined dynamically, , whatever method defined on instance run. since instance of class b
, , class b
overrides testa
, instance's version of testa
1 provided b
.
if in a.testa
want call a.testb
, have explicitly calling a.testb(self)
. however, should think why want that. whole point of overriding methods can change how class things. a
should not need know version of testb
called. should need know calling method called testb
whatever method testb
documented in program/library. if a
requires own testb
method called, makes difficult subclasses alter behavior of testb
, because a
ignore overrides , keep calling own version instead.
Comments
Post a Comment