从python类中引用外部作用域

2024-04-25 04:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

import tkinter as tk

__outerVar = {<dict stuff>}

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

当我尝试实例化编辑器时,我得到了关于使用NameError: name '_Editor__outerVar' is not defined的一个__outerVar。我试着把“global __outerVar”放在insideFunction的最上面,尽管我不是在给__outerVar写信,同样的错误。你知道吗

我肯定我只是误解了一些python范围规则。救命啊?你知道吗

第3.5页


Tags: 模块importselffortkinterdefasframe
2条回答

你看到的是这个名字在起作用。从documentation

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, as long as it occurs within the definition of a class.

据我所知,解决这个问题的唯一方法是将全局范围中的__outerVar重命名为不以双下划线开头的名称。你知道吗

Python替换前面带有双下划线__的任何名称,以便模拟“私有属性”。本质上__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就足够了。你知道吗

作为附录,在^{}中规定:

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.

所以,除非您设计的是子类名称冲突可能会引起问题的情况,否则不要使用双前导下划线。你知道吗

相关问题 更多 >