Cython 重载特殊方法?

发布于 2024-11-28 07:34:42 字数 1015 浏览 0 评论 0原文

是否有可能重载 __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) code> 未被识别为重载方法。

这是因为特殊方法不应定义为 cdef 并且只有 cdef-fed 函数可以重载?

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 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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

四叶草在未来唯美盛开 2024-12-05 07:34:42

我认为 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)
    ...

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)
    ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文