Over(joy)riding
Arnaud Delobelle
arnodel at googlemail.com
Wed Feb 17 09:25:06 EST 2010
mk <mrkafk at gmail.com> writes:
> Found in Dive into Python:
>
> """Guido, the original author of Python, explains method overriding
> this way: "Derived classes may override methods of their base
> classes. Because methods have no special privileges when calling other
> methods of the same object, a method of a base class that calls
> another method defined in the same base class, may in fact end up
> calling a method of a derived class that overrides it. (For C++
> programmers: all methods in Python are effectively virtual.)" """
>
> So, I set out to create such case:
>
> class A(object):
> def __init__(self):
> print "A"
>
> def met(self):
> print "I'm A's method"
>
> def overriden(self):
> print "I'm A's method to be overriden"
>
> def calling_overriden(self):
> self.overriden()
[...]
> class E(C,D):
> def __init__(self, arg):
> print "E", "arg=",arg
> C.__init__(self, arg)
> D.__init__(self, arg)
>
> def some(self):
> self.met()
>
> def overriden(self):
> print "I'm really E's method"
>
> e = E(10)
> print 'MRO:', ' '.join([c.__name__ for c in E.__mro__])
> e.some()
> e.calling_overriden()
>
>
> Result:
> ...
> MRO: E C A D B object
> I'm C's method
> I'm really E's method
>
>
> Is what I concocted in e.calling_overriden() == what Guido said on
> base class sometimes calling overriden method instead of its own
> original method?
Yes!
--
Arnaud
More information about the Python-list
mailing list