如何在没有类型问题的情况下对Python列表进行子类化? [英] How to subclass Python list without type problems?

查看:85
本文介绍了如何在没有类型问题的情况下对Python列表进行子类化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to implement a custom list class in Python as a subclass of list. What is the minimal set of methods I need to override from the base list class in order to get full type compatibility for all list operations?

此问题建议至少需要覆盖__getslice__.通过进一步的研究,还将需要__add____mul__.所以我有这段代码:

This question suggest that at least __getslice__ needs to be overridden. From further research, also __add__ and __mul__ will be required. So I have this code:

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))

即使没有覆盖方法,以下语句也可以按需工作:

The following statements work as desired, even without the overriding methods:

l = CustomList((1,2,3))
l.append(4)                       
l[0] = -1
l[0:2] = CustomList((10,11))    # type(l) is CustomList

这些语句仅适用于上述类定义中的覆盖方法:

These statements work only with the overriding methods in the above class definition:

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

我唯一不知道如何实现的是使扩展切片返回正确的类型:

The only thing I don't know how to achieve is making extended slicing return the right type:

l6 = l[0:2:2]                   # type(l6) is list

为了获得CustomList作为l6类型,我需要在类定义中添加什么?

What do I need to add to my class definition in order to get CustomList as type of l6?

还有,除了扩展切片之外,还有其他列表操作会导致结果是list类型而不是CustomList吗?

Also, are there other list operations other than extended slicing, where the result will be of list type instead of CustomList?

推荐答案

首先,我建议您遵循

Firstly, I recommend you follow Björn Pollex's advice (+1).

要解决此特定问题(type(l2 + l3) == CustomList),您需要实现自定义

To get past this particular problem (type(l2 + l3) == CustomList), you need to implement a custom __add__():

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

对于扩展切片:

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

我还建议...

pydoc list

...在命令提示符下.您将看到 list 公开了哪些方法,这将为您提供一个好方法指示您需要覆盖哪些.

...at your command prompt. You'll see which methods list exposes and this will give you a good indication as to which ones you need to override.

这篇关于如何在没有类型问题的情况下对Python列表进行子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆