且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建一个从C,它实现了一个__dict__一个Python类型?

更新时间:2023-11-30 14:16:58

以下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.