开发者

How can I create a static variable in a Python class via the C API?

I want to do the equivalent of

class Foo(object):
  bar = 1

using Pyth开发者_如何转开发on's C API. In other words, I want to create a Python class which has a static variable, using C.

How can I do this?


Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:

PyTypeObject type;
// ...other initialisation...
type.tp_dict = PyDict_New();
PyDict_SetItemString(type.tp_dict, "bar", PyInt_FromLong(1));


You can pass that source code to Py_CompileString with the appropriate flags.

If you already have the class you could use PyObject_SetAttr.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜