33.Python进阶_魔法方法__add__和__sub__

定义加号的操作,即当使用+操作时,将会触发__add__()方法
我们先看实例对象相加的情况:

class MyStr():
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return self.value

s1=MyStr('aaa')
s2=MyStr('BBBB')

print(s1)
print(s2)
print(s1+s2)

运行结果:

aaa
BBBB
Traceback (most recent call last):
  File "C:/workspace/pythonTest/pythonDemo/add.py", line 12, in 
    print(s1+s2)
TypeError: unsupported operand type(s) for +: 'MyStr' and 'MyStr'

发现会报错也就是两个实例对象无法直接相加
加入魔法方法__add__后再来看看:

class MyStr():
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return self.value
    def __add__(self, other):
        return f'{self.value}{other.value}'  #

s1=MyStr('aaa')
s2=MyStr('BBBB')

print(s1)
print(s2)
print(s1+s2)

运行结果:

aaa
BBBB
aaaBBBB

再来看看三个对象相加:

class MyStr():
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return self.value
    def __add__(self, other):
        return f'{self.value}{other.value}'  #

s1=MyStr('aaa')
s2=MyStr('BBBB')
s3=MyStr('ccc')

print(s1)
print(s2)
print(s1+s2)
print(s1+s2+s3)

运行结果:

aaa
Traceback (most recent call last):
BBBB
aaaBBBB
  File "C:/workspace/pythonTest/pythonDemo/add.py", line 16, in 
    print(s1+s2+s3)
TypeError: can only concatenate str (not "MyStr") to str

运行结果报错也就是说前两个实例对象相加后返回str,然后再和第三个实例对象相加所以报错,此刻我们将前两个返回结果转换为MyStr,

再修改一下:

class MyStr():
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return self.value
    def __add__(self, other):
        return MyStr(f'{self.value}{other.value}')  #

s1=MyStr('aaa')
s2=MyStr('BBBB')
s3=MyStr('ccc')

print(s1)
print(s2)
print(s1+s2)
print(s1+s2+s3)

运行结果:

aaa
BBBB
aaaBBBB
aaaBBBBccc

再看一下减法的形式,也就是字符串中去除:

class MyStr():
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return self.value
    def __add__(self, other):
        #return MyStr(f'{self.value}{other.value}')
        return MyStr('{}{}'.format(self.value,other.value))#\
    def __sub__(self, other):
        return self.value.replace(other.value,'')

s1=MyStr('aaaBBBB')
s2=MyStr('BBBB')
s3=MyStr('ccc')


print(s1)
print(s2)
print(s1+s2)
print(s1+s2+s3)
print(s1-s2)

运行结果:

aaaBBBB
BBBB
aaaBBBBBBBB
aaaBBBBBBBBccc
aaa

你可能感兴趣的:(Python进阶)