如何使用多个操作数重载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 官宣新年祝福语简短