【发布时间】:2017-02-09 03:30:18
【问题描述】:
我有点疑惑,为什么在 Python 中初始化一个类的实例时,我不能使用类属性。示例如下:
class TestClass:
... shared_list = ['a', 'b', 'c']
... def __init__(self):
... self.length = len(shared_list)
现在
>>> TestClass.shared_list
['a', 'b', 'c']
所以列表在类的任何实例出现之前就存在了,但是
>>> tc = TestClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
NameError: global name 'shared_list' is not defined
我错过了一些简单的东西吗?
UPD:感谢大家的帮助和及时回复。我已经消除了我的困惑:类在 Python 中没有定义范围。
【问题讨论】:
-
如果你想要作用域的
shared_list,你需要self.shared_list或TestClass.shared_list -
@AChampion 谢谢,把 TestClass.shared_list 修复它。来自 C++,我仍然觉得它很混乱,我需要一个明确的类的引用 within。我想如果在实例中找不到属性,就会在类中搜索,而不是全局搜索,不是吗?
-
很遗憾没有,请参阅上面的范围规则。