Cython cdef类不显示文档字符串或

2024-05-23 16:59:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用CDEF定义了一个Python类,它用Cython来封装C++类,并且它工作正常。但是当我在python或class中使用help(class)时呢?在ipython中,我得到了如下信息:

>>> TestClass.CTestClass?
Init signature: TestClass.CTestClass()
Docstring:      <no docstring>
File:               ~/Coding/CythonWithCppTutorials/ClassCythonCPPWithMemberFunctions/TestClass.so
Type:           type

它不显示任何doc字符串或init签名,我想显示它,如何让它显示这个?在

Cython包装如下:

在测试类.pyx在

^{pr2}$

和C++代码看起来是这样的:

在测试类c.cpp在

#include <iostream>

class TestClass{
public:
  TestClass(int Dimensionality, double* InputArray); // prototype of constructor
  ~TestClass(void); // prototype of destructor
  double SumListOfNumbers(void);
  int Dimensionality;
  double* ListOfNumbers;
};

TestClass::TestClass(int DIM, double* InputArray)
{
  Dimensionality = DIM;
  std::cout << Dimensionality << "\n";
  ListOfNumbers = new double[Dimensionality];
  for (int i = 0; i < Dimensionality; ++i) {
    ListOfNumbers[i] = InputArray[i];
    std::cout << ListOfNumbers[i] << ", ";
  }
  std::cout << "\n";
};

TestClass::~TestClass(void){
  std::cout << "Being Destroyed" << "\n";
};

double TestClass::SumListOfNumbers(void){
  double Sum = 0;
  for (int i = 0; i < Dimensionality; ++i) {
    Sum += ListOfNumbers[i];
  }
  return Sum;
}

Tags: ofcythonclassintstddoublesumprototype
1条回答
网友
1楼 · 发布于 2024-05-23 16:59:40

解决这个问题的方法是按照oz1的建议,将embedsignature指令设置为True,并添加一个普通的python __init__函数,如下所示:

@cython.embedsignature(True)
cdef class CTestClass: # defines a python wrapper to the C++ class
    """
    This is a test class wrapper for c++.
    """
    def __init__(self, Dimensionality, InputArray):
        pass

    cdef TestClass* thisptr # thisptr is a pointer that will hold to the instance of the C++ class


    def __cinit__(self, int Dimensionality, np.ndarray[double, ndim=1, mode="c"] InputArray not None): # defines the python wrapper class' init function
        cdef double[::1] InputArrayC = InputArray # defines a memoryview containnig a 1D numpy array - this can be passed as a C-like array by providing a pointer to the 1st element and the length
        self.thisptr = new TestClass(Dimensionality, &InputArrayC[0]) # creates an instance of the C++ class and puts allocates the pointer to this

然后init签名会自动包含在docstring中,如下所示:

^{pr2}$

相关问题 更多 >