如何在 Python 中进行多操作数的操作符重载?
你可以像为双操作符重载一样,在 Python 中使用多操作数操作符重载。例如,如果你想为一个类重载 + 操作符,你可以按照以下步骤进行 –
示例
class Complex(object):
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
real = self.real + other.real
imag = self.imag + other.imag
return Complex(real, imag)
def display(self):
print(str(self.real) + " + " + str(self.imag) + "i")
a = Complex(10, 5)
b = Complex(5, 10)
c = Complex(2, 2)
d = a + b + c
d.display()
输出
这将产生以下输出 –
17 + 17i
更多Python相关文章,请阅读:Python 教程
极客教程