在 __getitem__ 中实现切片 [英] Implementing slicing in __getitem__
问题描述
我正在尝试为我正在创建的创建向量表示的类实现切片功能.
到目前为止,我有这段代码,我相信它会正确实现切片,但是每当我调用 v[4]
之类的调用时,其中 v 是向量 python 会返回关于没有足够参数的错误.所以我想弄清楚如何在我的类中定义 getitem
特殊方法来处理普通索引和切片.
def __getitem__(self, start, stop, step):索引 = 开始如果停止 == 无:结束 = 开始 + 1别的:结束 = 停止如果步骤 == 无:步幅 = 1别的:步幅=步返回 self.__data[index:end:stride]
__getitem__()
方法将在对象被切片时接收一个 slice
对象.只需查看 slice
对象的 start
、stop
和 step
成员,即可获得用于切片.
I am trying to implement slice functionality for a class I am making that creates a vector representation.
I have this code so far, which I believe will properly implement the slice but whenever I do a call like v[4]
where v is a vector python returns an error about not having enough parameters. So I am trying to figure out how to define the getitem
special method in my class to handle both plain indexes and slicing.
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]
The __getitem__()
method will receive a slice
object when the object is sliced. Simply look at the start
, stop
, and step
members of the slice
object in order to get the components for the slice.
>>> class C(object):
... def __getitem__(self, val):
... print val
...
>>> c = C()
>>> c[3]
3
>>> c[3:4]
slice(3, 4, None)
>>> c[3:4:-2]
slice(3, 4, -2)
>>> c[():1j:'a']
slice((), 1j, 'a')
这篇关于在 __getitem__ 中实现切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!