Python对象加减法

"""
实现两个对象的相加,需实现类的__add__方法
实现两个对象的相减,需实现类的__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

猜你喜欢

转载自blog.csdn.net/zhu6201976/article/details/103883596