如何覆盖 python 中的 1/x 运算符

How to override 1/x operator in python

我正在 python 中创建一个 class,我想将其与我的自定义算术算法一起使用。为了对其实例进行操作,我重写了它的所有运算符函数,例如__add__、__mul__、__truediv__等

例如,假设它是一个复合体 class:

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's comment, I've just discovered the whole new world of Emulating numeric types

为什么不使用 in-built complex 类型和 cmath

a = 1+2j
b = 1/a

您需要定义__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)