Cython超载特殊方法?

时间:2011-08-08 22:19:18

标签: overloading cython

是否有可能超载__cinit____add__? 像这样:

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,
        )

调用Vector(0) + Vector(2, 4, 7)告诉我此处需要浮点数,因此似乎__add__(self, Vector other)不会被识别为重载方法。

这是因为特殊方法不应该被定义为cdef且只有cdef - 馈送功能可以重载吗?

1 个答案:

答案 0 :(得分:3)

我不认为在cython中支持运算符重载特殊函数。

最好的办法是手动创建类型检查逻辑并转换python对象 相应

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