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)
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中,有一个不推荐使用的方法,在子类化一些内置类型时可能需要覆盖它.
object.__getslice__(self, i, j)
自2.0版开始不推荐使用:支持切片对象作为
__getitem__()
方法的参数.(但是,CPython中的内置类型目前仍在实现__getslice__()
.因此,在实现切片时必须在派生类中重写它.)
这在Python 3中消失了.
执行此操作的正确方法是__getitem__
获取一个参数,该参数可以是数字,也可以是切片对象.
看到:
http://docs.python.org/library/functions.html#slice
http://docs.python.org/reference/datamodel.html#object.__getitem__
为了扩展Aaron的答案,numpy
你可以通过检查是否given
是tuple
:
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)
归档时间: |
|
查看次数: |
56512 次 |
最近记录: |