如何/为什么这在python中工作? rover._Dog__password()

我正在做
the python koan(对于python 2.6)并且发现了一些我不理解的东西.
One of the files在第160行中有以下代码:

class Dog(object):
    def __password(self):
        return 'password'

这个

rover = Dog()
password = rover.__password()

导致AttributeError.这对我来说很清楚. (__ password(self)是某种私有方法,因为前两个下划线).

但是这个

rover._Dog__password()

对我来说是一个谜.有人可以向我解释这是如何或为什么有效或更好地指向我所描述的文档?

最佳答案 双下划线:

Any identifier of the form __spam (at least two leading underscores,
at most one trailing underscore) is textually replaced with
_classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard
to the syntactic position of the identifier, so it can be used to
define class-private instance and class variables, methods, variables
stored in globals, and even variables stored in instances. private to
this class on instances of other classes.

所以当你调用__methodname时,它只是对_classname__methodname的调用.结果是AttributeError

单下划线:

具有前导下划线的类中的变量只是向其他程序员指示该变量应该是私有的.但是,变量本身并没有什么特别之处.

Python文档在这里:

Python private variables documentation

完整帖子在这里找到:

What is the meaning of a single- and a double-underscore before an object name?

点赞