82.如果要实现一种行为类似于内置函数列表的序列类型,则可以直接继承list:
举例:
class Countlist(list):
def __init__(self,*args):
super().__init__(*args)
self.count=0;
def __getitem__(self,index):
self.count+=1
return super(Countlist,self).__getitem__(index)
>>> a=Countlist(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.sort()
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.reverse()
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a.sort()
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[3:6]
>>> a
[0, 1, 2, 6, 7, 8, 9]
>>> a.count
0
>>> a[1]+a[3]
7
>>> a.count
2
结论:countlist类继承了超类list的行为,countlist没有重写的方法:例如append,extend,index等。都可以直接使用,在重写的方法中,都是调用super类调用超类的相应方法,并添加相应的行为,其中的count初始化在__init__()中,在__getitem__中更新count值。
本文介绍如何通过继承Python内置的list类来创建一个带有计数功能的新列表类Countlist。Countlist保留了list的所有特性,同时增加了对元素访问次数的计数。
3919

被折叠的 条评论
为什么被折叠?



