为什么不能在python中向对象添加属性?
(用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
:[…]
__slots__
声明采用一系列实例变量,并在每个实例中仅保留足够的空间来为每个变量保存一个值。因为__dict__
未为每个实例创建空间,所以节省了空间。编辑:要从评论中回答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__
,这是阻止属性动态分配的原因。我重新整理了答案,以使这一点更清楚(将第二段移到顶部)。
-
为什么不能在javascript中将属性添加到字符串对象?
2021-02-02 关注 0 浏览90 1答案
-
为什么我不能直接将属性添加到任何python对象?
2021-01-29 关注 0 浏览87 1答案
-
向python对象添加属性
2021-01-29 关注 0 浏览70 1答案
-
为什么允许向已实例化的对象添加属性?
2021-01-29 关注 0 浏览73 1答案
-
为什么我不能在python中创建轮子?
2021-01-29 关注 0 浏览101 1答案
-
为什么在Python中不能在循环前使用分号?
2021-01-29 关注 0 浏览68 1答案
-
为什么我不能在Python中设置全局变量?
2021-01-29 关注 0 浏览104 1答案
-
为什么我可以在字符串中添加字符,但不能在字符中添加字符?
2021-01-30 关注 0 浏览111 1答案
-
为什么我不能在 python 中创建一个轮子?
2022-07-28 关注 0 浏览11 1答案
-
为什么我不能在Python中扩展布尔值?
2021-01-29 关注 0 浏览84 1答案