在 __getitem__ 中实现切片 [英] Implementing slicing in __getitem__

查看:64
本文介绍了在 __getitem__ 中实现切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我正在创建的创建向量表示的类实现切片功能.

到目前为止,我有这段代码,我相信它会正确实现切片,但是每当我调用 v[4] 之类的调用时,其中 v 是向量 python 会返回关于没有足够参数的错误.所以我想弄清楚如何在我的类中定义 getitem 特殊方法来处理普通索引和切片.

def __getitem__(self, start, stop, step):索引 = 开始如果停止 == 无:结束 = 开始 + 1别的:结束 = 停止如果步骤 == 无:步幅 = 1别的:步幅=步返回 self.__data[index:end:stride]

解决方案

__getitem__() 方法将在对象被切片时接收一个 slice 对象.只需查看 slice 对象的 startstopstep 成员,即可获得用于切片.

<预><代码>>>>C类(对象):... def __getitem__(self, val):... 打印 val...>>>c = C()>>>c[3]3>>>c[3:4]切片(3、4、无)>>>c[3:4:-2]切片(3, 4, -2)>>>c[():1j:'a']切片((), 1j, 'a')

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆