我有一个(简化的)模块,像这样:
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 byFoo.__a
. (An insistent user could still gain access by callingFoo._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/