开发者

Cython overload Special Methods?

Is there a possibility to overload __cinit__ or __add__ ? Something like this:

cdef class Vector(Base):
    cdef double x, y, z

    def __cinit__(self, double all):
        self.x = self.y = self.z = all

    def __cinit__(self, double x, double y, double z):
        self.x  = x
        self.y  = y
        self.z  = z

    def __str__(self):
        return "Vector(%s, %s, %s)" % (self.x, self.y, self.z)

    def __add__(self, Vector other):
        return Vector(
            self.x + other.x,
            self.y + other.y,
            self.z + other.z,
        )

    def __add__(self, object other):
        other   = <double>other
        return Vector(
            self.x + other.x,
            self.y + other.y,
            self.z + other.z,
        )

Calling Vector(0) + Vector(2, 4, 7) tells me that a开发者_Python百科 float is required here, so it seems like __add__(self, Vector other) is not recognized as an overloaded method.

Is this because Special methods should not be defined as cdef and only cdef-fed functions can be overloaded ?


I don't think that operator overloading of special functions is supported in cython.

your best bet is to create manually the type checking logic and cast the python object accordingly.

def __add__(self, other):
    if type(other) is float:
        return self.__add__(<double> other)
    elif isinstance(other,Vector):
        return self.__add__(<Vector> other)
    ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜