如何使用多个操作数重载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
热门推荐
10 送离职同事简短祝福语
11 小红书生日祝福语简短
12 祝产妇的祝福语简短
13 水晶婚夫妻祝福语简短
14 年后祝福语简短走心
15 别人怀孕的简短祝福语
16 汤姆猫祝福语简短霸气
17 律所年会祝福语简短
18 关于早晨的祝福语简短