如何将 python c 扩展方法声明为类方法?

问题描述 投票:0回答:1

我正在为一个 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()
对应的是什么?

python python-c-api
1个回答
8
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.