Python笔记(二十七)_魔法方法_容器
定制容器
容器类型的协议:
定制不可变容器,只需要定义__len__()和__getitem__()方法
定制可变容器,需要定义__len__()、__getitem__()、__setitem__()和_delitem__()方法
__len__(self): 定义当被len()调用时的行为,返回容器中的个数
__getitem__(self,key): 定义获取容器中指定元素的行为,相当于self[key]
__setitem__(self,key,value): 定义设置容器中指定元素的行为,相当于self[key]=value
__delitem__(self,key): 定义删除容器中指定元素的行为,相当于del self[key]
class CountList(list):
def __init__(self, *args):
super().__init__(args)
self.count = []
for i in args:
self.count.append(0)
def __len__(self):
return len(self.count)
def __getitem__(self, key):
self.count[key] += 1
return super().__getitem__(key)
def __setitem__(self,key,value):
self.count[key] += 1
super().__setitem__(key,value)
def __delitem__(self,key):
del self.count[key]
super().__delitem__(key)
def counter(self,key):
return self.count[key]
def append(self,value):
self.count.append(0)
super().append(value)
def pop(self,key):
del self.count[key]
return super().pop(key)
def remove(self,value):
key=super().index(value)
del self.count[key]
super().remove(value)
def insert(self,key,value):
self.count.insert(key,0)
super().insert(key,value)
def clear(self):
self.count.clear()
super().clear()
def reverse(self):
self.count.reverse()
super().reverse()
转载于//www.cnblogs.com/demilisi/p/11048209.html
还没有评论,来说两句吧...