1、python类与对象各个算术运算魔法方法总结:
2、各个魔法方法应用举例:
3、实例训练:
(1)我们都知道在 Python 中,两个字符串相加会自动拼接字符串,但遗憾的是两个字符串相减却抛出异常。因此,现在我们要求定义一个 Nstr 类,支持字符串的相减操作:A – B,从 A 中去除所有 B 的子字符串。
class Nstr(str):
def __sub__(self,other):
self=list(self)
other=list(other)
for i in other:
c=len(self)
while(c>0):
if i in self:
self.remove(i)
c=c-1
x=""
for j in range(len(self)):
x=x+self[j]
return x
a = Nstr('I love iiiiii FishC.com!iiiiiiii')
b = Nstr('i')
print(a-b)
(2)定义一个类 Nstr,当该类的实例对象间发生的加、减、乘、除运算时,将该对象的所有字符串的 ASCII 码之和进行计算:
class Nstr(str):
def __add__(self,other):
y=0
z=0
for i in self:
x=ord(i)
y=y+x
for j in other:
q=ord(j)
z=z+q
return int(y)+int(z)
def __sub__(self,other):
y=0
z=0
for i in self:
x=ord(i)
y=y+x
for j in other:
q=ord(j)
z=z+q
return int(y)-int(z)
def __mul__(self,other):
y=0
z=0
for i in self:
x=ord(i)
y=y+x
for j in other:
q=ord(j)
z=z+q
return int(y)*int(z)
def __truediv__(self,other):
y=0
z=0
for i in self:
x=ord(i)
y=y+x
for j in other:
q=ord(j)
z=z+q
return int(y)/int(z)
def __floordiv__(self,other):
y=0
z=0
for i in self:
x=ord(i)
y=y+x
for j in other:
q=ord(j)
z=z+q
return int(y)//int(z)