我想在 Python 中实现一个自定义列表类作为list
。我需要从基础重写的最小方法集是什么list
类以获得所有列表操作的完全类型兼容性?
这个问题 https://stackoverflow.com/questions/2235556/python-subclass-builtin-list建议至少__getslice__
需要被覆盖。从进一步的研究来看,还__add__
and __mul__
将被要求。所以我有这个代码:
class CustomList(list):
def __getslice__(self,i,j):
return CustomList(list.__getslice__(self, i, j))
def __add__(self,other):
return CustomList(list.__add__(self,other))
def __mul__(self,other):
return CustomList(list.__mul__(self,other))
即使没有覆盖方法,以下语句也可以按需要工作:
l = CustomList((1,2,3))
l.append(4)
l[0] = -1
l[0:2] = CustomList((10,11)) # type(l) is CustomList
这些语句仅适用于上述类定义中的重写方法:
l3 = l + CustomList((4,5,6)) # type(l3) is CustomList
l4 = 3*l # type(l4) is CustomList
l5 = l[0:2] # type(l5) is CustomList
我唯一不知道如何实现的是使扩展切片返回正确的类型:
l6 = l[0:2:2] # type(l6) is list
我需要在类定义中添加什么才能获得CustomList
作为类型l6
?
另外,除了扩展切片之外,是否还有其他列表操作,其结果为list
键入而不是CustomList
?