python魔法方法汇总_python类与对象各个魔法方法总结

1、python类与对象各个魔法方法总结:

20181205101622718227.png

2、各个魔法方法应用举例:

20181205101623223077.png

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)

20181205101623647855.png

(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)

20181205101624098021.png

原文地址:https://www.cnblogs.com/Yanjy-OnlyOne/p/10068828.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值