如何在没有类型问题的情况下对Python列表进行子类化?

2024-10-01 17:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python中实现一个自定义列表类作为list的子类。为了获得所有列表操作的完整类型兼容性,我需要从基类list重写的最小方法集是什么?

This question建议至少需要重写__getslice__。进一步的研究还需要__add____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


Tags: 方法selfadd类型列表returnisdef
2条回答

首先,我建议您遵循Björn Pollex's advice(+1)。

要解决这个特殊问题(type(l2 + l3) == CustomList),需要实现一个自定义的^{}

   def __add__(self, rhs):
        return CustomList(list.__add__(self, rhs))

对于extended slicing

    def __getitem__(self, item):
        result = list.__getitem__(self, item)
        try:
            return CustomList(result)
        except TypeError:
            return result

我也推荐。。。

pydoc list

…在你的命令提示下。您将看到^{}公开了哪些方法,这将很好地指示您需要重写哪些方法。

您可能应该阅读文档中的以下两部分:

编辑:为了处理扩展切片,应该使__getitem__-方法处理切片对象(请参阅here,再往下一点)。

相关问题 更多 >

    热门问题