蟒蛇:动态添加属性到内置类

问题描述:

为什么它不针对内置类工作?

Why doesn't it work for the built-in classes?

时使用一个子类,最好的办法来解决它,否则我会碰到一些隐藏的问题?

Is using a subclass the best approach to fix it, or will I run into some hidden problems?

a = {}
a.p = 1 # raises AttributeError
class B(dict):
  pass
b = B()
b.p = 1 # works

编辑:我原来的评论,它不适合工作b 是不正确的(我犯了一个错误)

my original comment that it doesn't work for b was incorrect (I made a mistake).

内建类不必有任意属性的能力。这是对的性能,尤其是内存使用情况的原因做了,你想要的内置类如列表字典来尽可能小,所以你可以有很多。

The builtin classes do not have the ability to have arbitrary attributes. This is done for reasons of performance, especially memory usage, you want the built-in classes like list and dict to be as small as possible so you can have many of them.

因此​​有内置类不被需要的任意属性的工作 __ __字典词典。

Therefore the built-in classes do not have the __dict__ dictionary that is needed for arbitrary attributes to work.

您也可以达到同样为你的类。如果他们是用C你根本不落实 __ __字典支持。如果他们是用Python编写的使用插槽

You can achieve the same for your classes. If they are written in C you simply do not implement the __dict__ support. If they are written in Python you use slots.