gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:17 25 4
gpt4 key购买 nike

我有一个关于 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'

关于python - 关于 Python 和类特定变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20335798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com