我正在尝试构建一个基于内置列表类型的类:
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
。这些函数被记录为(几乎)总是生成一个列表
。如果您还传递其他类型的序列,它们也会这样做。
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/