python - 如何从类访问 Python 模块的私有(private)变量

标签 python python-3.x scope name-mangling

在 Python 3 中,为类变量添加前缀使其私有(private),我可以在类中修改名称。如何访问类中的模块变量?

比如下面两种方式都行不通:

__a = 3
class B:
    def __init__(self):
        self.a = __a
b = B()

结果是:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
NameError: name '_B__a' is not defined

使用 global也没有帮助:
__a = 3
class B:
    def __init__(self):
        global __a
        self.a = __a
b = B()

结果是:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NameError: name '_B__a' is not defined

运行 locals()显示变量 __a存在未损坏:
>>> locals()
{'__package__': None, '__name__': '__main__',
 '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
 '__doc__': None, '__a': 3, 'B': <class '__main__.B'>,
 '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}

[添加换行符以提高可读性]

在模块中运行相同的代码(而不是解释器)会导致完全相同的行为。使用 Anaconda 的 Python 3.5.1 :: Continuum Analytics, Inc. .

最佳答案

这很丑陋,但您可以访问全局变量:

__a = 3
class B:
    def __init__(self):
        self.a = globals()["__a"]
b = B()

你也可以把它放在一个字典中:
__a = 3

d = {"__a": __a}

class B:
    def __init__(self):
        self.a = d["__a"]
b = B()

或者一个列表、元组等......和索引:
__a = 3

l = [__a]

class B:
    def __init__(self):
        self.a = l[0]
b = B()

关于python - 如何从类访问 Python 模块的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34621484/

相关文章:

C++ 类变量析构函数

python - Python set 比 list 更节省空间吗?

python - 使用用户输入验证对方法进行单元测试

mysql - 内部错误 : (1242, 'Subquery returns more than 1 row' )

Python 正则表达式 : Match ALL consecutive capitalized words

python : UnicodeEncodeError: 'charmap' codec can't encode character '\u2190' in position 2936

c++ - 无法在枚举中声明 "div"

javascript - JavaScript中变量的范围是什么?

python - 将 print 语句添加到 ValueError 异常

python - 如何使用python创建com对象