首先,我要说的是,为什么子类list不能像您预期的那样工作(因为list是一个原始的内置类型,并且存在性能问题等等)。AFAIK collections.UserList应该避免所有这些问题,并使子类UserList完全像您所期望的那样工作。例如,
class DumbList(list):
pass
d1 = DumbList([1,2,3])
d2 = DumbList([4,5])
type(d1 + d2)返回<class 'list'>,但是
from collections import UserList
class DumbList(UserList):
pass
d1 = DumbList([1,2,3])
d2 = DumbList([4,5])
type(d1 + d2)按预期返回<class '__main__.DumbList'>。然而,切片似乎返回错误的类型,即使使用UserList而不是list。
class DumbList(UserList):
pass
d = DumbList([1,2,3])
type(d[:2])返回<class 'list'>,而不是预期的<class '__main__.DumbList'>。
两个问题:
class DumbList(UserList):
def __getitem__(self, item):
result = UserList.__getitem__(self, item)
try:
return self.__class__(result)
except TypeError:
return result...but,似乎这种锅炉板代码应该是不必要的.
发布于 2014-12-18 17:37:59
在Python2中,普通切片(没有跨步)将由方法处理。UserList实现比在语言中添加扩展片(带步幅)早,并且从未增加对它们的支持,请参阅第491398期。
Python3实现只是采用Python2版本,进入collections并删除了__getslice__和__setslice__,因为这些在Python3中不再支持。
因此,__getitem__实现仍然是简单的:
def __getitem__(self, i): return self.data[i]假设切片会在其他地方处理。
在Python3中,所有切片都是通过将内建式传递给__getitem__来处理的;只需测试该类型并在type(self)调用中包装结果:
def __getitem__(self, i):
res = self.data[i]
return type(self)(res) if isinstance(i, slice) else reshttps://stackoverflow.com/questions/27552379
复制相似问题