Skip to main content
 首页 » 编程设计

python之关于 Python 和类特定变量的问题

2025年05月04日13TianFang

我有一个关于 python 和类初始化变量的问题。

所以我最近在 Python (2.7.X) 中注意到,如果您设置了一个尚未定义或初始化的类变量,您仍然可以调用和访问该变量中的数据。

例如:

class Test: 
    def __init__(self): 
        self.a = "Hello" 
 
 
t = Test() 
print t.a 
t.b = "World" 
print t.b 

输出:

Hello 
World 

我预计 'print t.b' 会出错,因为 b 尚未在 Test() 类中定义,但它运行时没有任何问题。为什么会这样?谁能解释一下?

http://ideone.com/F2LxLh

感谢您的宝贵时间。

请您参考如下方法:

来自 instance objects 上的文档(t 是实例对象,因为它是自定义类 Test 的实例):

Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to.

但是您可以使用 __slots__ 获得预期的行为用new-style class .这会覆盖属性的默认字典存储,使对象的内存效率更高,如果您尝试分配给 __slots__ 中未定义的属性,它还会导致 AttributeError,例如:

>>> class Test(object): 
...     __slots__ = ['a'] 
... 
>>> t = Test() 
>>> t.a = "Hello" 
>>> t.b = "World" 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'Test' object has no attribute 'b'