我正在用python创建一个类,我想将它与我的自定义算术算法一起使用。为了对它的实例进行操作,我已经重写了它的所有操作符函数,比如uu add\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
例如,假设它是一个复杂的类:
class complex:
def __init__(self,module,phase):
self.module = module
self.phase = phase
def __mul__(self,other):
return complex(self.module + other.module, self.phase + other.phase)
def __truediv__(self,other):
return complex(self.module / other.module, self.phase - other.phase)
我希望能够将表达式写成:
from math import pi
a = complex(1,0.5*pi)
b = 1/a
但如果我这样做,我会得到以下错误:
不支持/:“int”和“complex”的操作数类型
而我想知道
b = complex(1,0) / a
我必须重写什么才能让它工作?你知道吗
编辑:
多亏了hiro protagonist的评论,我才发现了Emulating numeric types的全新世界
您需要定义
__rtruediv__(self,other)
,这是当您的对象位于除法的右侧时使用的函数。你知道吗或许对其他运营商来说:
您可以使用已有的其他选项来定义这些选项:
为什么不使用内置的
complex
类型和cmath?你知道吗相关问题 更多 >
编程相关推荐