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)
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 cython 不支持特殊函数的运算符重载。
你最好的选择是手动创建类型检查逻辑并强制转换 python 对象
因此。
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.