Python:在__getitem__中实现切片

nic*_*ine 99 python slice python-datamodel

我正在尝试为我正在创建的类创建切片功能,以创建矢量表示.

到目前为止我有这个代码,我相信它会正确地实现切片,但每当我做一个调用,就像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)

Ign*_*ams 108

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')
Run Code Online (Sandbox Code Playgroud)

  • 注意:对于扩展内置类型(如list或tuple),必须为python 2.X版本实现`__getslice__`.请参阅https://docs.python.org/2/reference/datamodel.html#object.__getslice__ (10认同)
  • @Eric:不,因为第二个冒号的存在绕过了`__get/set/delslice__`.不过,它非常微妙. (3认同)

Wal*_*sen 62

我有一个"合成"列表(数据大于你想要在内存中创建的那个),我__getitem__看起来像这样:

def __getitem__( self, key ) :
    if isinstance( key, slice ) :
        #Get the start, stop, and step from the slice
        return [self[ii] for ii in xrange(*key.indices(len(self)))]
    elif isinstance( key, int ) :
        if key < 0 : #Handle negative indices
            key += len( self )
        if key < 0 or key >= len( self ) :
            raise IndexError, "The index (%d) is out of range."%key
        return self.getData(key) #Get the data from elsewhere
    else:
        raise TypeError, "Invalid argument type."
Run Code Online (Sandbox Code Playgroud)

切片不会返回相同的类型,这是禁忌,但它适用于我.


Aar*_*all 15

如何定义getitem类来处理普通索引和切片?

当您使用的下标符号结肠切片对象被自动创建-而正是传递给__getitem__.使用isinstance来检查,如果你有一个切片对象:

from __future__ import print_function

class Sliceable(object):
    def __getitem__(self, subscript):
        if isinstance(subscript, slice):
            # do your handling for a slice object:
            print(subscript.start, subscript.stop, subscript.step)
        else:
            # Do your handling for a plain index
            print(subscript)
Run Code Online (Sandbox Code Playgroud)

用法示例:

>>> range(1,100, 4)[::-1]
range(97, -3, -4)
Run Code Online (Sandbox Code Playgroud)

Python 2,请注意:

在Python 2中,有一个不推荐使用的方法,在子类化一些内置类型时可能需要覆盖它.

datamodel文档:

object.__getslice__(self, i, j)

自2.0版开始不推荐使用:支持切片对象作为__getitem__()方法的参数.(但是,CPython中的内置类型目前仍在实现__getslice__().因此,在实现切片时必须在派生类中重写它.)

这在Python 3中消失了.

  • 这应该是接受的答案. (2认同)

car*_*arl 7

执行此操作的正确方法是__getitem__获取一个参数,该参数可以是数字,也可以是切片对象.

看到:

http://docs.python.org/library/functions.html#slice

http://docs.python.org/reference/datamodel.html#object.__getitem__


Eri*_*eau 6

为了扩展Aaron的答案,numpy你可以通过检查是否giventuple:

class Sliceable(object):
    def __getitem__(self, given):
        if isinstance(given, slice):
            # do your handling for a slice object:
            print("slice", given.start, given.stop, given.step)
        elif isinstance(given, tuple):
            print("multidim", given)
        else:
            # Do your handling for a plain index
            print("plain", given)

sliceme = Sliceable()
sliceme[1]
sliceme[::]
sliceme[1:, ::2]
Run Code Online (Sandbox Code Playgroud)

```

输出:

('plain', 1)
('slice', None, None, None)
('multidim', (slice(1, None, None), slice(None, None, 2)))
Run Code Online (Sandbox Code Playgroud)