I was trying out NVI(Non-Virtual Interface) Idiom in python, and noticed that private(double underscore) methods don’t seem to be acting as virtual.
class A(object):
def a(self):
print "in A.a"
self.b()
self.__b()
self._b()
def _b(self):
print "in A._b"
def __b(self):
print "in A.__b"
def b(self):
print "in A.b"
class B(A):
def __b(self):
print "in B.__b"
def b(self):
print "in B.b"
def _b(self):
print "in B._b"
>>> a=A()
>>> b=B()
>>> a.a()
in A.a
in A.b
in A.__b
in A._b
>>> b.a()
in A.a
in B.b
in A.__b
in B._b
I am guessing this may have been because of name mangling for double underscore methods, but it is counter-intuitive. Further, confusion arises from python documentation “(For C++ programmers: all methods in Python are effectively virtual.)”.
As the documentation says, double-leading-underscore methods are for class-private members. They are private to the specific class in which they are used, not to its class inheritance subtree. That is the point: they are designed for class-specific variables whose values you don’t want subclass definitions to override, or subclass methods to access.
You are correct that the name-mangling is the source of the behavior you describe. All Python methods are indeed virtual in that they can be overridden. The double-underscore methods just make access from outside the class harder by mangling the name. You could override
A.__bby defining a method_A__bin classB. That would be a bad idea because it would be subverting the purpose of using double-underscores in the first place, but it is possible.