欢迎光临散文网 会员登陆 & 注册

Python大神必会的对象加减法,一定要掌握。

2021-04-10 11:44 作者:薇薇说UG  | 我要投稿


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


Python大神必会的对象加减法,一定要掌握。的评论 (共 条)

分享到微博请遵守国家法律