Class vs instance initialization in Python
我有点困惑,为什么在Python中初始化类的实例时,我不能使用类属性。示例如下:
1 2 3 4 | class TestClass: ... shared_list = ['a', 'b', 'c'] ... def __init__(self): ... self.length = len(shared_list) |
现在
1 2 | >>> TestClass.shared_list ['a', 'b', 'c'] |
所以列表在类的任何实例出现之前就存在了,但是
1 2 3 4 5 | >>> 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 |
我错过了简单的东西吗?
谢谢大家的帮助和及时的回复。我已经澄清了我的困惑:类没有在Python中定义范围。
When a class definition is entered, a new namespace is created, and
used as the local scope — thus, all assignments to local variables go
into this new namespace. In particular, function definitions bind the
name of the new function here.When a class definition is left normally (via the end), a class object
is created. This is basically a wrapper around the contents of the
namespace created by the class definition.
这就是为什么您需要在方法中引用类属性为
问题出现在
1 2 | def __init__(self): self.length = len(TestClass.shared_list) |
如果只想修改该实例的变量,则必须将其声明为实例变量:
1 2 3 | def __init__(self): self.not_shared_list = ['a', 'b', 'c'] self.length = len(self.not_shared_list) |
如果您没有指定变量
使用