I write a test code of python like:
class Parent(object):
@classmethod
def dispatch(klass):
print 'klass = %s' % klass
return klass().__dispatch()
def __dispatch(self):
print 'This Parent.__dispatch()'
print self
class Child(Parent):
def __dispatch(self):
print 'This Child.__dispatch()'
print self
if __name__=='__main__':
print 'Calling Parent.dispatch() ...\n'
Parent.dispatch()
print ''
print 'Calling Child.dispatch() ...\n'
Child.dispatch()
print '\n-END'
And the output is:
Calling Parent.dispatch() ...
klass = <class '__main__.Parent'>
This Parent.__dispatch()
<__main__.Parent object at 0x0000000002D3A2E8>
Calling Child.dispatch() ...
klass = <class '__main__.Child'>
This Parent.__dispatch()
<__main__.Child object at 0x0000000002D3A2E8>
-END
It’s very strange why the overwrote method ‘__dispatch(self)’ of Child class was not called.
Does anyone can explain about this?
Thank you.
Methodnames that start with a double underscore are automatically mangled; internally, the string
_ClassNameis prepended to the method name:This renaming also is done for anything referencing this method name in any of the other methods in the class.
Thus, your
__dispatch()method is renamed to_Parent__dispatch(), and thedispatch()method is altered to callself._Parent__dispatch()instead. Similarly, yourChildclass has a_Child__dispatch()method, and it thus does not override the_Parent__dispatch()method of it’s super-class.This is why you see the results you see; rename your
__dispatch()methods to_dispatch()(only one underscore) and it’ll work as expected.Why does python do this? It’s a form of providing private attributes and methods, that cannot be accidentally overridden by classes that inherit from them. See private name mangling in the Python expression reference.
The PEP 8 Python Style Guide has this to say about private name mangling: