Python学习笔记(二十一)——小甲鱼第四十二讲
0、工厂函数是类对象,调用它们的时候是创建一个相应的实例对象
1、a+b时会根据a的__add__魔法方法进行加法操作
2、当类的属性名和方法名相同时属性名会覆盖方法名
4、鸭子风格
0、
>>>
class Nstr(str):
def __sub__(self,other):
return self.replace(other,'')
运行结果
>>> a = Nstr('I love you iiiiiii')
>>> b = Nstr('i')
>>> a - b
'I love you '
1、
class Nstr(str):
def __lshift__(self,other):
return self[other:] + self[:other]
def __rshift__(self,other):
return self[:-other] + self[-other:]
运行结果
>>> a = Nstr('I love you')
>>> a << 3
'ove youI l'
>>> a >> 3
'I love you'
2、
class Nstr():
def __init__(self,arg=''):
if isinstance(arg,str):
self.total = 0
for each in arg:
self.total += ord(each)
else:
print('参数错误')
def __add__(self,other):
return self.total + other.total
def __sub__(self,other):
return self.total - other.total
def __mul__(self,other):
return self.total * other.total
def __floordiv__(self,other):
return self.total // other.total
运行结果
>>> a = Nstr('love')
>>> b = Nstr('happy')
>>> a + b
984
>>> a - b
-108
>>> a * b
239148
>>> a // b
0
>>>