[英]Extend list class with inplace slicing
I am trying to write a class that inherits from the Python list
class and has a method that does inplace slicing (original object modified). 我正在尝试编写一个从Python
list
类继承的类,并且该类具有进行切片的方法(已修改原始对象)。
This is what I have: 这就是我所拥有的:
class MyList(list):
def __init__(self, mylist = []):
list.__init__(self)
self.extend(mylist)
def slice_it(self, x):
self = self[:x]
return self
And then I instantiate it: 然后我实例化它:
>>> 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]
I would expect the last output to be [1, 2, 3]. 我希望最后的输出是[1、2、3]。 Any ideas?
有任何想法吗?
You are simply assigning to the local variable self
, this won't mutate the list. 您只是将其分配给局部变量
self
,这不会改变列表。 You have to use a mutator method, so try: 您必须使用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 action: 实际上:
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]
Note, you can actually make this work with slice-notation: 注意,您实际上可以使用切片符号来完成这项工作:
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]
How's that for a fluent interface? 界面流畅如何?
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.