您可以对多个操作数执行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