[]在Python中覆盖类的运算符(下标表示法)的方法名称是什么?
我正在尝试为我正在创建的类创建切片功能,以创建矢量表示.
到目前为止我有这个代码,我相信它会正确地实现切片,但每当我做一个调用,就像v[4]v是一个向量python返回一个关于没有足够的参数的错误.所以我试图弄清楚如何getitem在我的类中定义特殊方法来处理普通索引和切片.
def __getitem__(self, start, stop, step):
index = start
if stop == None:
end = start + 1
else:
end = stop
if step == None:
stride = 1
else:
stride = step
return self.__data[index:end:stride]
Run Code Online (Sandbox Code Playgroud) 我在Python中创建一个容器类,它将继承list或仅实现所有标准列表方法(我真的不关心哪个).
如何创建仅对切片返回的项目起作用的方法?我已经能够制作一个能够作用于整个容器的方法(见下文),但我似乎无法弄清楚如何仅对切片采取行动.
我正在使用python 2.7.6并from __future__ import print_function, division在我的所有代码中使用.
示例代码:
from __future__ import print_function, division
import itertools
class MyContainerClass(list):
""" For now, I'm inheriting from list. Is this my problem? """
def __init__(self, data_array):
list.__init__(self, data_array)
def __getitem__(self, *args):
arg = args[0]
# specific indices MyContainerClass[0, 3, 5] => indexes 0, 3, and 5
if isinstance(arg, (list, tuple)) and not isinstance(arg[0], bool):
return [list.__getitem__(self, _i) for _i in arg]
# standard slice notation
elif isinstance(arg, slice):
return …Run Code Online (Sandbox Code Playgroud) 假设我有如下列表:
lst = [0,10,20,30,40,50,60,70]
Run Code Online (Sandbox Code Playgroud)
我想要按循环顺序从 lst 从index = 5到 的元素。index = 2
lst[5:2]产量[]
我想要的lst[5:2] = [50,60,70,0,10]。有没有简单的库函数可以做到这一点?
使用Python列表
L=[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
我希望L[m] = 0如果m不同0,1,2,3,即:
...
L[-2]=0
L[-1]=0
L[0]=1
L[1]=2
L[2]=3
L[3]=4
L[4]=0
L[5]=0
Run Code Online (Sandbox Code Playgroud)
和
L[-2:2] = [0, 0, 1, 2]
Run Code Online (Sandbox Code Playgroud)
这不适用于经典列表或数组.这样做的好方法是什么?
编辑:这是一个很好的解决方案(由一个答案给出):
class MyList(list):
def __getitem__(self, index):
return super(MyList, self).__getitem__(index) if index >= 0 and index < len(self) else 0
Run Code Online (Sandbox Code Playgroud)
但我仍然无法拥有
L[-2:2] = [0, 0, 1, 2]
Run Code Online (Sandbox Code Playgroud)