Python:继承内置列表类型VS过滤器、map内置函数

标签 python subclass

我正在尝试构建一个基于内置列表类型的类:

class MyList(list):

    def __getslice__(self, i, j):
        return MyList(
            super(MyList, self).__getslice__(i, j)
        )

    def __add__(self,other):
        return MyList(
            super(MyList, self).__add__(other)
        )

    def __mul__(self,other):
        return MyList(
            super(MyList, self).__mul__(other)
        )

    def __getitem__(self, item):
        result = super(MyList, self).__getitem__(item)
        try:
            return MyList(result)
        except TypeError:
            return result

我想知道是否有一种方法可以使 MyList 类与过滤器或 map 等内置函数一起使用。我所说的“使用”是指使过滤器和映射返回 MyList 类对象而不是列表类型对象。

>>> a = MyList([1, 2, 3, 4])
>>> type(a)
<class '__main__.MyList'>
>>> b = filter(lambda this: this > 2, a)
>>> type(b)
<type 'list'>

我希望 type(b) 返回与 type(a) 相同的返回值。

有什么建议吗?

最佳答案

不,您必须将 filter()map() 的输出转换回 MyList。这些函数被记录为(几乎)总是生成一个列表。如果您还传递其他类型的序列,它们也会这样做。

引自map() documentation :

The iterable arguments may be a sequence or any iterable object; the result is always a list.

换句话说,filter()map() 不关心您传入的序列的确切类型,这并不限于您的 MyList 类型。

异常(exception)是 filter(),它是 tuple()str() 的特殊情况;引用 filter() documentation :

If iterable is a string or a tuple, the result also has that type; otherwise it is always a list.

这种特殊处理是硬编码的,无法扩展。在Python 3中,这个异常(exception)不再适用; map()filter() 都返回一个生成器

关于Python:继承内置列表类型VS过滤器、map内置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17922220/

相关文章:

python - 我可以在命令行中运行 Jupyter 笔记本单元格吗?

Python:float 的子类可以在其构造函数中使用额外的参数吗?

cocoa - clickedRow (NSTableView) 的子类

Java 子类一般概念

python - Snakemake:在 Expand() 中使用正则表达式

python - 计算Python中数字的标准差

python - 对 numpy ndarray 进行子类化时,如何正确修改 __getitem__?

python - Python 集中的散列行为

python - 使用粒子群优化进行适当的编码

python - 如何获取和修改嵌套字典的值?