如何在Python中实现__slots__? [英] How is __slots__ implemented in Python?

查看:74
本文介绍了如何在Python中实现__slots__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • How is __slots__ implemented in Python?
  • Is this exposed in the C interface?
  • How do I get __slots__ behaviour when defining a Python class in C via PyTypeObject?

推荐答案

创建Python类时,默认情况下它们具有__dict__,您可以在它们上设置任何属性.插槽的重点是不创建__dict__来节省空间.

When creating Python classes, they by default have a __dict__ and you can set any attribute on them. The point of slots is to not create a __dict__ to save space.

相反,在C接口中,扩展类默认情况下没有__dict__,而您必须显式地添加一个扩展类并添加getattr/setattr支持来处理它(尽管幸运的是,有一些方法可以做到这一点) PyObject_GenericGetAttrPyObject_GenericSetAttr已经存在,所以您不必实现它们,只需使用它们即可.(有趣的是,还没有PyObject_GenericDelAttr,但我不确定这是怎么回事.(我应该停止嵌套括号了)这样(或不这样))).

In the C interface it's the other way around, an extension class has by default no __dict__, and you would instead explicitly have to add one and add getattr/setattr support to handle it (although luckily there are methods for this already, PyObject_GenericGetAttr and PyObject_GenericSetAttr, so you don't have to implement them, just use them. (Funnily there is not PyObject_GenericDelAttr, though, I'm not sure what that is about. (I should probably stop nesting parenthesis like this (or not)))).

因此,不需要插槽,对于扩展类型也没有意义.默认情况下,您只允许您的getattr/setatttr方法仅访问类具有的那些属性.

Slots therefore aren't needed nor make sense for Extension types. By default you just let your getattr/setatttr methods access only those attributes that the class has.

关于其实现方式,代码位于 typeobject.c 中,这几乎只是一个问题:如果对象具有__slots__属性,请不要创建__dict__.非常令人兴奋.:-)

As for how it's implemented, the code is in typeobject.c, and it's pretty much just a question of "If the object has a __slots__ attribute, don't create a __dict__. Quite unexciting. :-)

这篇关于如何在Python中实现__slots__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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