python - 这在 python 中如何/为什么起作用?流浪者._Dog__password()

标签 python class syntax methods private

我在做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) 是某种私有(private)方法,因为前导有两个下划线)。

但是这个

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

单下划线:

类中带有前导下划线的变量只是为了向其他程序员表明该变量应该是私有(private)的。但是,变量本身没有做任何特别的事情。

此处为 Python 文档:

Python private variables documentation

在这里找到完整的帖子:

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

关于python - 这在 python 中如何/为什么起作用?流浪者._Dog__password(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8869847/

相关文章:

python - 如何在python2中捕获在python3中运行的命令的输出?

functional-programming - defun 和 defstruct 中的百分号

r - %op% 运算符是什么意思?例如 "%in%"?

python - 如何使用PyTorch打印出每个类别的预测准确率?

python - 将带有元素日期标签的年度财政数据元组 Munge 转换为 Python Pandas 中的时间序列

python - 将 3 字节立体声 WAV 文件转换为 numpy 数组

C++ header 和声明嵌套结构和类语法

python - 如何从 tkinter 中的单选按钮获取值?

java - 如何使用类 - 蓝牙线程

rust - 为什么对不明确的数字进行方法调用会导致错误?