python - 从 python 类引用外部范围

标签 python class python-3.x module scope

我有一个(简化的)模块,像这样:

import tkinter as tk

__outerVar = {<dict stuff>}

class Editor(tk.Frame):
...
    def _insideFunction(self):
        for p in __outerVar.keys():
            <do stuff>

当我尝试实例化编辑器时,我在使用 __outerVar 时收到 NameError: name '_Editor__outerVar' is not defined。我尝试将“global __outerVar”放在 insideFunction 的顶部,即使我没有写入 __outerVar,同样的错误。

我确定我只是误解了这里的一些 python 作用域规则。帮忙?

py 3.5

最佳答案

Python 会替换所有以双下划线 __ 开头的名称,以模拟“私有(private)属性”。本质上 __name 变成了 _classname__name。这称为名称修改,仅发生在记录的类中 in the docs :

This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

解决方案是不要使用 __name 名称,使用类似 _name 的名称或仅使用 name 就足够了。

作为附录,在 PEP 8 -- Method Names and Instance Variables它指出:

Python mangles these names with the class name: if class Foo has an attribute named __a , it cannot be accessed by Foo.__a . (An insistent user could still gain access by calling Foo._Foo__a.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

因此,除非您设计的情况是子类名称冲突可能是个问题,否则请不要使用双前导下划线。

关于python - 从 python 类引用外部范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398019/

相关文章:

python - 如何修复 bs4 选择错误 : 'TypeError: __init__() keywords must be strings'

Python 类型检查器 mypy : subprocess. STARTUPINFO 未定义

python - 数据框 set_index 未设置

java - 程序的两个部分中从未达到 If 和 Else 语句

python - 有效地找到 OrderedDictionary 中的上一个键

python - scapy 没有发送数据包

python - 多参数Tensorflow分类程序

python - 重构这个分组密码键控函数

javascript - 试图理解 JavaScript 中原型(prototype)的意义

class - 在 Swift 中创建对象类