Python大神必會的對象加減法,一定要掌握。

實現(xiàn)兩個對象的相加,需實現(xiàn)類的__add__方法
實現(xiàn)兩個對象的相減,需實現(xiàn)類的__sub__方法
complex
1 + 2j
3 + 4j
"""
?
?
class Complex(object):
?
? ? def __init__(self, x, y):
? ? ? ? self.x = x
? ? ? ? self.y = y
?
? ? def __add__(self, other):
? ? ? ? self.x += other.x
? ? ? ? self.y += other.y
?
? ? def __sub__(self, other):
? ? ? ? self.x -= other.x
? ? ? ? self.y -= other.y
?
? ? def show_add(self):
? ? ? ? print('%d + %dj' % (self.x, self.y))
?
? ? def show_sub(self):
? ? ? ? print('%d + %dj' % (self.x, self.y))
?
?
c1 = Complex(1, 2)
c2 = Complex(3, 4)
# c1 + c2
c1.__add__(c2)
c1.show_add()? # 4 + 6j
# c1 - c2
c1.__sub__(c2)
c1.show_sub()? # 1 - 2j
標(biāo)簽: