是否有可能重载 __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)
告诉我这里需要一个 float ,所以看起来像 __add__(self, Vector other)
未被识别为重载方法。
这是因为特殊方法不应定义为 cdef
并且只能重载 cdef
函数吗?
最佳答案
我认为 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)
...
关于overloading - Cython 重载特殊方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6989301/