0

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.)".

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
skydeep
  • 3
  • 1

2 Answers2

1

Your analysis is correct. This is due to name mangling, which effectively makes A.__b unrelated to B.__b (since they have different mangled names).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

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.__b by defining a method _A__b in class B. 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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Whether or not it's a bad idea is a matter of perspective ;-) -- As the idiom goes, "We're all consenting adults here". But it certainly isn't something that should be done without a lot of thought. – mgilson Jan 30 '13 at 19:23