python写一个类_从C创建一个Python类型来实现一个?

下面的代码将生成一个在Python 2.x中实现__dict__的类: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);

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值