|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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=-1):
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()
###小甲鱼的除了len()和init()其他的魔法方法都
使用了super函数调用基类的同名方法,这是为什么啊
class CountList:
def __init__(self,*args):
self.List = [x for x in args]
self.count = {}.fromkeys( [x for x in args], 0)
def __len__(self):
return len(self.List)
def __getitem__(self,index):
key = self.List[index]
self.count[key] += 1
return self.List[index]
def __setitem__(self,index,value):
key = self.List[index]
self.List[index] = value
self.count.pop(key)
self.count[value] = 0
def append(self,value):
self.List.append(value)
self.count[value] = 0
def pop(self):
key = self.List[len(self.List)-1]
self.count.pop(key)
self.List.pop()
def remove(self,value):
if value not in self.List:
print('列表不存在该元素!')
else:
self.List.remove(value)
self.count.pop(value)
def insert(self,index,value):
self.List.insert(index,value)
self.count[value] = 0
def clear(self):
self.count.clear()
return self.List.clear()
def reverse(self):
self.List.reverse() # list.reverse() 这一步操作的返回值是一个None
return self.List # 需要通过打印被作用的列表才可以查看出具体的效果
def counter(self,index):
key = self.List[index]
return self.count[key]
###我自己的代码没有用super函数但是也能运行,暂时还没有发现bug
那使用super函数到底有什么用呢? |
|