gpt4 book ai didi

python - 为什么不能在 python 中为对象添加属性?

转载 作者:IT老高 更新时间:2023-10-28 20:21:10 24 4
gpt4 key购买 nike

(用 Python shell 编写)

>>> o = object()
>>> o.test = 1

Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass

>>> t = test1()
>>> t.test

Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
pass

>>> t = test2()
>>> t.test = 1
>>> t.test
1
>>>

为什么对象不允许你给它添加属性?

最佳答案

注意 object 实例没有 __dict__ 属性:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']

在派生类中说明此行为的示例:

>>> class Foo(object):
... __slots__ = {}
...
>>> f = Foo()
>>> f.bar = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'

引用 slots 上的文档:

[...] The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

编辑:从评论中回答 ThomasH,OP 的测试类是一个“旧式”类。试试:

>>> class test: pass
...
>>> getattr(test(), '__dict__')
{}
>>> getattr(object(), '__dict__')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__dict__'

您会注意到有一个 __dict__ 实例。对象类可能没有定义 __slots__,但结果是一样的:缺少 __dict__,这是阻止动态分配属性的原因。我已经重新组织了我的答案以使其更清晰(将第二段移到顶部)。

关于python - 为什么不能在 python 中为对象添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1285269/

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