python - 带双下划线的变量名的奇怪行为

标签 python

下面的代码没有显示错误。

class Bar():
    pass

class Foo():
    def __init__(self):
        self.__bar = Bar()

    def get_bar(self):
        return self.__bar

foo = Foo()
bar1 = foo.get_bar()

foo.__bar = Bar()
bar2 = foo.get_bar()

assert (bar1 is bar2)

为什么 __bar 表现得像单例?

最佳答案

因为双下划线are magical :Python 会修改这些名称,以便无法从类外部访问它们。

如果您要将示例的最后三行替换为...

foo._Foo__bar = Bar()
bar2 = foo.get_bar()

assert (bar1 is bar2)

...您会看到您期望的行为。

关于python - 带双下划线的变量名的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38895544/

相关文章:

python - 使用opencv python从视频检测图像时如何忽略背景?

python - 如何将列表转换为使用元组作为键的字典

python - 为什么显示收敛失败?

python - <class 'str'> 和 <type 'str' > 有什么区别

python - 如何错误检查 Python 统计模式功能?

python - 如何根据某些条件合并数据集的行

python - 为什么自定义 Python 对象不能与 ParDo Fn 一起使用?

python - 如何将 .ui 文件转换为 .py 文件

python - 通过差值和总和进行分组

python - numpy.dot -> MemoryError, my_dot -> 非常慢,但有效。为什么?