蟒蛇:动态添加属性到内置类 [英] python: dynamically adding attributes to a built-in class

查看:154
本文介绍了蟒蛇:动态添加属性到内置类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于蟒蛇:动态添加属性到内置类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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