如何在没有类型问题的情况下继承Python列表?

2024-04-08

我想在 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?


首先,我建议您关注比约恩·波莱克斯的建议 https://stackoverflow.com/questions/8180014/how-to-subclass-python-list-without-type-problems/8180073#8180073 (+1).

为了解决这个特殊问题(type(l2 + l3) == CustomList),你需要实现一个自定义__add__() http://docs.python.org/reference/datamodel.html#object.__add__:

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

And for 扩展切片 http://docs.python.org/release/2.3.5/whatsnew/section-slices.html:

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

我还推荐...

pydoc list

...在命令提示符下。您将看到哪些方法list http://docs.python.org/library/functions.html#list暴露,这将为您提供一个很好的指示,告诉您需要覆盖哪些内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在没有类型问题的情况下继承Python列表? 的相关文章

随机推荐