[英]How to define static class attributes in Python from C++?
I wonder how can I define a static class variable from C++ for Python? 我想知道如何从C ++ for Python定义静态类变量? The equivalent Python code would be like: 等效的Python代码如下所示:
class foo:
bar = int
I tried to use tp_getset field when defining the type, but it turns out it doesn't work and returns a getset_descriptor
in Python, and it doesn't work when called on instances (AttributeError). 我尝试在定义类型时使用tp_getset字段,但事实证明它不起作用,并在Python中返回了getset_descriptor
,并且在实例上调用时不起作用(AttributeError)。 Furthermore, Python doc says directly manipulating tp_dict
with C API is unsafe. 此外,Python文档说直接使用C API操纵tp_dict
是不安全的。 But it doesn't tell what to use instead. 但是它并没有告诉我们要使用什么。 (see here ) (请参阅此处 )
I deliberately chose int
in the example since I'm referencing some other class in it, if that matters. 我故意在示例中选择int
,因为如果有关系,我将在其中引用其他类。
The tp_getset
defines descriptors for a type; tp_getset
定义类型的描述符 ; descriptors are bound to instances when accessed via the __getattribute__
hook, so are not suitable to define class attributes. 描述符通过__getattribute__
钩子访问时绑定到实例,因此不适合定义类属性。
You can add attributes to a class by setting them on the PyTypeObject.tp_dict
object for the type; 您可以通过在类型的PyTypeObject.tp_dict
对象上设置属性来将属性添加到类。 do so in the module's initialization function ( PyInit_<modulename>
), for example, after finalising the type with PyType_Ready()
(which makes sure the tp_dict
object exists): 例如,在使用PyType_Ready()
完成类型PyType_Ready()
确保tp_dict
对象存在)之后,在模块的初始化函数( PyInit_<modulename>
)中执行以下操作:
PyObject *d;
PyObject *bar;
d = PyFoo_Type.tp_dict;
bar = PyLong_FromLong(42);
if (bar == NULL || PyDict_SetItemString(d, "bar", bar) < 0)
return NULL;
Py_DECREF(bar);
This is untested C code; 这是未经测试的C代码; I'm not familiar enough with C++ to confidently provide you with a C++ version instead. 我对C ++不够熟悉,无法自信地为您提供C ++版本。
If you want to see a real-life example, see the datetime
module , where the datetime.min
, datetime.max
, etc. class attributes are set. 如果要查看真实示例,请参阅datetime
模块 ,其中设置了datetime.min
, datetime.max
等类属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.