|
4鱼币
- class CountList(list):
- def __init__(self, *args):
- [color=Red]super().__init__(args)[/color]
- 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()
复制代码
为什么那里还要调用父类的__init__(args)???
list本身有__init__方法,比如,把一个字符串变成列表。
>>> a = list('abc')
>>> a
['a', 'b', 'c']
CountList首先要有这个方法,其次还要
self.count = []
for i in args:
self.count.append(0)
办法有2个,一是调用父类的__init__,而是自己重写list的__init__功能,
|
最佳答案
查看完整内容
list本身有__init__方法,比如,把一个字符串变成列表。
>>> a = list('abc')
>>> a
['a', 'b', 'c']
CountList首先要有这个方法,其次还要
self.count = []
for i in args:
self.count.append(0)
办法有2个,一是调用父类的__init__,而是自己重写list的__init__功能,
|