简体   繁体   English

python:将属性动态添加到内置类

[英]python: dynamically adding attributes to a built-in class

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). 编辑:我原来的评论,它不适用于b是不正确的(我犯了一个错误)。

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. 这样做是出于性能方面的考虑,尤其是内存使用方面的原因,您希望内置类(如listdict尽可能小,以便可以拥有许多此类。

Therefore the built-in classes do not have the __dict__ dictionary that is needed for arbitrary attributes to work. 因此,内置类没有__dict__字典,任意属性才能正常工作。

You can achieve the same for your classes. 您可以为自己的课程取得相同的成绩。 If they are written in C you simply do not implement the __dict__ support. 如果它们是用C编写的,则根本就不实现__dict__支持。 If they are written in Python you use slots . 如果它们是用Python编写的,则使用slot

If you want to subclass dict you can always use UserDict ( here the documentation ). 如果要对dict进行子类化,则可以始终使用UserDict在此文档中 )。

And it works with what you're trying to do: 它可以与您要执行的操作一起使用:

from collections import UserDict

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM