重载加法运算
class NewList(list):
def __add__(self,other):
result=[]
for i in range(len(self)):
try:
result.append(self[i]+other[i])
except:
result.append(self[i])
return result
ls=NewList([1,2,3,4,5,6])
lt=NewList([1,2,3,4])
print(ls+lt)
输出:
[2, 4, 6, 8, 5, 6]
重载小于运算
实现两个列表的和的比较
class NewList(list):
def __lt__(self,other):
s,t=0,0
for c in self:
s+=c
for c in other:
t+=c
return True if s<t else False
ls=NewList([6,1,2,3])
lt=NewList([1,2,3,99])
print([6,1,2,3]<[1,2,3,99])
print(ls<lt)
输出:
False
True
成员运算的重载
列表的元素和也包含在列表中
class NewList(list):
def __contains__(self,item):
s=0
for c in self:
s+=c
if super().__contains__(item) or item==s:
return True
else:
return False
ls=NewList([6,1,2,3])
print(6 in ls,12 in ls)
输出:
True True
其他运算的重载
class NewList(list):
def __format__(self,format_spec):
"格式化输出,以三逗号分隔"
t=[]
for c in self:
if type(c) ==type("字符串"):
t.append(c)
else:
t.append(str(c))
return ",,,".join(t)
ls=NewList([1,2,3,4])
print(format([1,2,3,4]))
print(format(ls))
输出:
[1, 2, 3, 4]
1,,,2,,,3,,,4