简体   繁体   中英

PYTHON: virtual method behavior differences for public, private(single underscore) and private(double underscore) methods

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM