我正在尝试编写一个继承自Python list
类的类,并且有一个方法可以进行inplace切片(修改原始对象)。
这就是我所拥有的:
class MyList(list):
def __init__(self, mylist = []):
list.__init__(self)
self.extend(mylist)
def slice_it(self, x):
self = self[:x]
return self
然后我实例化它:
>>> mylist = MyList(mylist=[1,2,3,4,5])
>>> mylist
[1, 2, 3, 4, 5]
>>> mylist.slice_it(3)
[1, 2, 3]
>>> mylist
[1, 2, 3, 4, 5]
我希望最后的输出为[1,2,3]。有什么想法吗?
答案 0 :(得分:2)
您只是分配给本地变量self
,这不会改变列表。你必须使用mutator方法,所以试试:
class MyList(list):
def __init__(self, mylist = None):
list.__init__(self)
if mylist is not None:
self.extend(mylist)
def slice_it(self, x):
self[:] = self[:x]
return self
行动中:
In [10]: mylist = MyList(mylist=[1,2,3,4,5])
In [11]: mylist
Out[11]: [1, 2, 3, 4, 5]
In [12]: mylist.slice_it(3)
Out[12]: [1, 2, 3]
In [13]: mylist
Out[13]: [1, 2, 3]
注意,您实际上可以使用切片符号来实现此功能:
In [30]: from itertools import islice
...: class MyList(list):
...: def __init__(self, mylist = []):
...: list.__init__(self)
...: self.extend(mylist)
...: def __getitem__(self, x):
...: if isinstance(x, slice):
...: self[:] = islice(self, x.start, x.stop, x.step)
...: return self
...: else:
...: return list.__getitem__(self, x)
...:
In [31]: mylist = MyList(mylist=range(20))
In [32]: mylist[::2]
Out[32]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [33]: mylist
Out[33]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [34]: mylist[0]
Out[34]: 0
In [35]: mylist
Out[35]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
如何使用流畅的界面?
In [36]: mylist = MyList(mylist=range(100))
In [37]: mylist[::2][:10]
Out[37]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [38]: mylist
Out[38]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]