|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 指尖、行 于 2017-7-26 21:27 编辑
运行结果如下:
>>> list1 = Countlist('a', 'b', 5, 6)
>>> list1.pop(2)
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
list1.pop(2)
File "J:/python/python exercise/47 lesson/0 homework.py", line 28, in pop
return super( ).pop(index)
AttributeError: 'super' object has no attribute 'pop'
以下是代码:
class Countlist:
def __init__(self, *args):
self.values = [x for x in args]
self.count = {}.fromkeys(self.values, 0)# 按每个值来记录访问次数
def __len__(self):
return len(self.values)
def __getitem__(self, key):
self.countkey = self.values[key] #取出列表中的元素作为字典self.count的key值
self.count[self.countkey] += 1
return self.values[key]
def __setitem__(self, key, value):
del self.count[self.values[key]] #删除原来的键值对应的访问次数
self.values[key] = value # 给列表赋值
self.count[value] = 0 #将访问次数置0
def __delitem__(self, key):
del self.count[self.values[key]] #删除原来的键值对应的访问次数
del self.values[key]
def counter(self, index):
return self.count[self.values[index]]
def pop(self, index):
del self.count[self.values[index]] #删除原来的键值对应的访问次数
return super( ).pop(index)
super()是继承父类的__init__()方法的,你定义的类Countlist根本就不是一个子类,你是想让它继承于内置函数list吧,这样你就需要把list作为Countlist的父类的
|
|