python: dynamically adding attributes to a built-in class

烈酒焚心 提交于 2019-12-04 06:25:21

问题


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

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


回答1:


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.

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.




回答2:


If you want to subclass dict you can always use UserDict (here the documentation).

And it works with what you're trying to do:

from collections import UserDict

a = UserDict()
a.p = 10 # works fine


来源:https://stackoverflow.com/questions/8843140/python-dynamically-adding-attributes-to-a-built-in-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!