If the instances of this type have a dictionary containing instance
variables, this field is non-zero and contains the offset in the
instances of the type of the instance variable dictionary; this offset
is used by PyObject_GenericGetAttr().
Do not confuse this field with tp_dict; that is the dictionary for
attributes of the type object itself.
首先回答最后一个问题:不,
type_new
只用于在运行时动态定义的“堆类型”(例如通过class语句)。静态定义的类型使用PyType_Ready()
初始化。在要回答第一个问题:要使用
__dict__
描述符创建扩展类型,需要像解释器为类定义所做的那样动态分配类型。在获取例子的一种方法是按照John的建议来做,并用Cython生成一些自己的例子。在
对于cpython2.x,您可以查看CPython源代码(http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup)中的
build_class
方法,以了解完全通用解决方案中涉及的步骤。在如果您使用的是python3,那么这个问题可能会引起您的兴趣:What does Python's builtin __build_class__ do?
也就是说,作为一个特定于cpython3.x的解决方案,最简单的方法就是通过C API使用适当的参数调用
builtins.__build_class__
。在我还没有这样做,我在使用C-API方面很糟糕,但是根据文档,使用}来使用}方法就足够了。当然,您还需要一个名为
PyObject_GenericGetAttr
和{getattro
和{__dict__
的PyObject属性。在你试过了吗?在
下面的代码将生成一个在Python 2.x中实现
__dict__
的类:重要的位是
PyTypeObject
结构(http://docs.python.org/c-api/typeobj.html)的tp_dictoffset
成员:相关问题 更多 >
编程相关推荐