读书笔记:
重打代码:
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) #计数为0
super().insert(key,value)
def clear():
self.count.clear()
super().clear()
def reverse(self):
self.count.reverse()
super().reverse()
>>> list1 = CountList(1,2,3)
>>> list1
[1, 2, 3]
>>> list1.count
[0, 0, 0]
>>> list1[0]
1
>>> list1.count
[1, 0, 0]
>>> list1.counter(0)
1
>>> list1.append(4)
>>> list1
[1, 2, 3, 4]
>>> list1.remove(1)
>>> list1.pop(0)
2
>>> list1
[3, 4]
>>> list1.extend([8,8])
>>> list1
[3, 4, 8, 8]
>>> list1.count(3)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
list1.count(3)
TypeError: 'list' object is not callable
>>> list1.count(1)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list1.count(1)
TypeError: 'list' object is not callable