overloading - Cython 重载特殊方法?

标签 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) 告诉我这里需要一个 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/

相关文章:

c++ - 将 NULL 作为参数传递时,函数重载如何工作?

r - R 中引用类的函数重载?

c++ - 为什么编译器选择这个模板函数而不是重载的非模板函数?

java - 想要在运行时 java 中动态传递 class.getmethod 参数

java - Java 中方法重载的确切需要

python - numpy数组比较的高效Python实现

Python,如何优化这段代码

multithreading - Cython 并行 prange - 线程局部性?

python - 尝试在 Windows 8.1 上安装 kivy

python - 对象成员的 Cython 缓冲区声明