龙空技术网

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

UG编程教程 155

前言:

当前各位老铁们对“python 相减”都比较重视,小伙伴们都想要分析一些“python 相减”的相关内容。那么小编同时在网摘上搜集了一些对于“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

标签: #python 相减