如何将python c-extension方法声明为classmethod?

时间:2013-11-12 20:57:08

标签: python python-c-api

我正在为C ++类编写一个python包装器,它为备用“构造函数”提供了几种静态方法。我想知道如何通过python c-api导出这些?

这是相关C ++代码的存根。

 PyObject *PyFoo_FromFoo(Foo foo);

 // This should be a class method that create a new instance of PyFoo().
 PyObject *
 PyFoo_Gen1(PyObject *self, PyObject *args)
 {
     Foo foo;  // Init this according to args

     return PyFoo_FromFoo(foo);
 }

 static PyMethodDef PyFoo_methods[] = {
    {"Gen1", (PyCFunction)PyFoo_Gen1, METH_VARARGS, "Gen1 foo creator" },
    {NULL}  /* Sentinel */
 };

 PyTypeObject PyFooType = {
   :
   PyFoo_methods, /* tp_methods */
   :
 }

 PyObject *PyFoo_FromFoo(Foo foo)
 {
    PyFoo *v = (PyFoo*)PyObject_New(PyFoo, &PyFooType);
    v->foo = foo;
    return (PyObject*)v;
 }

在上面的示例中,对classmethod()使用@classmethod函数(直接或通过Gen1()装饰器)对应的是什么?

1 个答案:

答案 0 :(得分:4)

从python 2.3开始,可以使用METH_CLASS完成。有关示例,请参阅datetime模块。