Cython and constructors of classes

六月ゝ 毕业季﹏ 提交于 2020-01-01 17:27:06

问题


I have a problem with Cython usage of default constructors.

My C++ class Node is the following

Node.h

class Node
{
public:
    Node()
    { 
        std::cerr << "calling no arg constructor" << std::endl;
            w=0.0;
        d=0.0;
    }
    Node(double val, double val2);
    {
            std::cerr << "calling 2 args constructor" << std::endl;
        this->w=val;
        this->d=val2;
    }
private:
    double d,w;
}

is wrapped in Cython as follows

cdef extern from "Node.h":
    cdef cppclass Node:
        Node() except +
        Node(double val1, double val2) except +
        double d
        double w

cdef class pyNode:
    cdef Node *thisptr      # hold a C++ instance which we're wrapping

    def __cinit__(self):
        self.thisptr = new Node()

    def __cinit__(self, double val1, double val2):
        self.thisptr = new Node(val1,val2)

    def __dealloc__(self):
        del self.thisptr

    def __repr__(self):
        return "d=%s w=%s" % (self.thisptr.w, self.thisptr.w )

The Cython code compiles well, but in particular when called from Python

from pyNode import pyNode as Node
n=Node(1.0,2.0)

I get the expected calling 2 args constructor string, but if I'm trying to declare a Node object from python using the "no-arguments" constructor (which should be correctly declared as __cinit__(self) I'm getting no output, this means that the no-argument constructor is not called!

How can I explicitly call it from the cinit method of the wrapped class?


回答1:


The issue here is that you can't overload __cinit__() like that (as only cdef functions can be overloaded) - instead, have it take default values, then call the right thing as needed.

Edit: Essentially, you need to implement the function in a way closer to how you would in normal Python code, instead of using overloading:

def __cinit__(self, double val1=-1, double val2=-1): 
    if val1 == -1 or val2 == -1:
        self.thisptr = new Node()
    else:
        self.thisptr = new Node(val1,val2)

Naturally, this presumes -1 is a value that isn't useful for the function, you could use another value, or if you need every value of a double to be valid, then you might need to remove the typing, taking a Python object so that you can use None as the default:

def __cinit__(self, val1=None, val2=None):
    if val1 is not None and val2 is not None:
        self.thisptr = new Node(val1, val2)
    else:
        self.thisptr = new Node()


来源:https://stackoverflow.com/questions/13201886/cython-and-constructors-of-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!