如何在python中重写1/x运算符

2024-10-04 03:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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的全新世界


Tags: 实例函数self算法addreturndefpi
2条回答

您需要定义__rtruediv__(self,other),这是当您的对象位于除法的右侧时使用的函数。你知道吗

或许对其他运营商来说:

def __radd__(self, other):       ... 
def __rsub__(self, other):       ...
def __rmul__(self, other):       ...
def __rmatmul__(self, other):    ...
def __rfloordiv__(self, other):  ...
def __rmod__(self, other):       ...
def __rdivmod__(self, other):    ...

您可以使用已有的其他选项来定义这些选项:

def __rtruediv__(self,other):
    return complex(other,0).__truediv__(self)

为什么不使用内置的complex类型和cmath?你知道吗

a = 1+2j
b = 1/a

相关问题 更多 >