创建一个从C,它实现了一个__dict__一个Python类型? [英] Create a Python type from C that implements a __dict__?

查看:236
本文介绍了创建一个从C,它实现了一个__dict__一个Python类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 如何创建有一个 __ __字典按正常类将是它在Python界定?
  • 类型
  • 是否有与 __ __字典 S'
  • 非动态类型的任何实例
  • 请通过Python的<一个定义的类型href=\"http://svn.python.org/view/python/branches/py3k/Include/object.h?view=markup&sortby=date\"><$c$c>PyTypeObject通过<一个href=\"http://svn.python.org/view/python/branches/py3k/Objects/typeobject.c?view=markup&sortby=date\"><$c$c>type_new?

  • How is a type created to have a __dict__ as per a "normal" class would have were it defined in Python?
  • Are there any examples of non-dynamic types with __dict__s?
  • Do types defined via Python's PyTypeObject pass through type_new?

PyTypeObject tp_dict 成员,但我可以找到如何使用它的信息。此外,还似乎有什么东西在 typeobject.c 怎么回事的 type_new 但我不能清楚地破译它。

There is a tp_dict member of PyTypeObject, but I can find no information on how it's used. There also seems to be something going on in typeobject.c's type_new but I can't decipher it clearly.

下面是我发现了一些相关的信息:

Here is some related information I've found:

  • __dict__ in class inherited from C extension module
  • How is __slots__ implemented in Python?

推荐答案

以下code将产生一个实现类 __字典__ 在Python 2.x的:

The following code will generate a class that implements a __dict__ in Python 2.x:

typedef struct {
  PyObject_HEAD
  PyObject* dict;
} BarObject;

static PyTypeObject BarObject_Type = {
  PyObject_HEAD_INIT(NULL)
};

PyMODINIT_FUNC
initFoo(void)
{
  PyObject *m;

  m = Py_InitModule("Foo", NULL);
  if (m == NULL)
    return;

  BarObject_Type.tp_new = PyType_GenericNew;
  BarObject_Type.tp_name = "Foo.Bar";
  BarObject_Type.tp_basicsize = sizeof(BarObject);
  BarObject_Type.tp_getattro = PyObject_GenericGetAttr;
  BarObject_Type.tp_setattro = PyObject_GenericSetAttr;
  BarObject_Type.tp_flags = Py_TPFLAGS_DEFAULT;
  BarObject_Type.tp_dictoffset = offsetof(BarObject,dict);
  BarObject_Type.tp_doc = "Doc string for class Bar in module Foo.";
  if (PyType_Ready(&BarObject_Type) < 0)
    return;

  Py_INCREF(&BarObject_Type);
  PyModule_AddObject(m, "Bar", (PyObject*)&BarObject_Type);
}

最重要的一点是 PyTypeObject 结构的 tp_dictoffset 成员(的http://docs.python.org/c-api/typeobj.html ):

如果有这种类型的实例含有实例的字典
  变量,该字段不为零,并且包含在所述偏移
  实例变量词典的类型的实例;这个偏移
  使用由PyObject_GenericGetAttr()

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

不要混淆这个领域与tp_dict;也就是字典
  属性类型对象本身。

Do not confuse this field with tp_dict; that is the dictionary for attributes of the type object itself.

这篇关于创建一个从C,它实现了一个__dict__一个Python类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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