您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

请注意,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__,这是阻止属性动态分配的原因。我重新整理了答案,以使这一点更清楚(将第二段移到顶部)。

python 2022/1/1 18:32:54 有204人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶