How is __slots__ implemented in Python?

风流意气都作罢 提交于 2019-12-06 20:16:28

问题


  • 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?

回答1:


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.

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)))).

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.

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. :-)



来源:https://stackoverflow.com/questions/5057845/how-is-slots-implemented-in-python

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