I saw an example today of a method overriding a method in a base class that had a different name, how and why is this possible? And what uses could it possibly have?
>>> class A(object):
... def foo(self):
... self.__bar()
... def __bar(self):
... print "original"
...
>>> class B(A):
... def _A__bar(self):
... print "overridden"
...
>>> B().foo()
overridden
Wow, that is really horrible.
This works because methods that begin with a double-underscore – the
__barmethod inA– are name-mangled as a very basic way of simulating “private” functions in Python. But they’re not actually private, they’re just prefixed with_classname. So the coder here is taking advantage of this to override the so-called private method in A.This works, but you shouldn’t ever do it. (In fact, you should almost never use the double-underscore private attributes anyway, but that’s a different discussion.)