为python对象添加属性 [英] Adding attributes to python objects

查看:75
本文介绍了为python对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这件事困扰了我一段时间.为什么我做不到:

<预><代码>>>>一个 = "">>>a.foo = 2回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'str' 对象没有属性 'foo'

...虽然我可以执行以下操作?

<预><代码>>>>类酒吧():... 经过...>>>a = 酒吧()>>>a.foo = 10 #ok!

这里的规则是什么?你能指点我一些描述吗?

解决方案

您可以向任何具有 __dict__ 的对象添加属性.

  • x = object() 没有它,例如.
  • 字符串和其他简单的内置对象也没有.
  • 使用 __slots__ 的类也没有.
  • class 定义的类都有它,除非前面的语句适用.

如果一个对象正在使用 __slots__/没有 __dict__,通常是为了节省空间.例如,在 str 中,如果有一个 dict 就有点矫枉过正了——想象一下一个非常短的字符串的膨胀量.

如果你想测试给定的对象是否有__dict__,你可以使用hasattr(obj, '__dict__').

这个阅读起来可能也很有趣:

<块引用>

某些对象,例如内置类型及其实例(列表、元组等)没有 __dict__.因此,无法对它们设置用户定义的属性.

另一篇关于 Python 数据模型的有趣文章,包括 __dict____slots__ 等,是 this 来自 python 参考.

It's a thing that bugged me for a while. Why can't I do:

>>> a = ""
>>> a.foo = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'foo'

...while I can do the following?

>>> class Bar():
...     pass
... 
>>> a = Bar()
>>> a.foo = 10 #ok!

What's the rule here? Could you please point me to some description?

解决方案

You can add attributes to any object that has a __dict__.

  • x = object() doesn't have it, for example.
  • Strings and other simple builtin objects also don't have it.
  • Classes using __slots__ also do not have it.
  • Classes defined with class have it unless the previous statement applies.

If an object is using __slots__ / doesn't have a __dict__, it's usually to save space. For example, in a str it would be overkill to have a dict - imagine the amount of bloat for a very short string.

If you want to test if a given object has a __dict__, you can use hasattr(obj, '__dict__').

This might also be interesting to read:

Some objects, such as built-in types and their instances (lists, tuples, etc.) do not have a __dict__. Consequently user-defined attributes cannot be set on them.

Another interesting article about Python's data model including __dict__, __slots__, etc. is this from the python reference.

这篇关于为python对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆