[英]Python slice objects and __getitem__
python中是否存在內容,以不同方式處理傳遞給__getitem_ _
參數,並自動將start:stop:step
構造轉換為切片?
這是我的意思的演示
class ExampleClass(object):
def __getitem__(self, *args):
return args
def __call__(self, *args):
return args
def randomMethod(self, *args):
return args
a = ExampleClass()
#this works
print a[3:7:2, 1:11:2]
#syntax error on the first colon
print a.randomMethod(3:7:2, 1:11:2)
print a(3:7:2, 1:11:2)
#these work
print a.randomMethod(slice(3,7,2), slice(1,11,2))
print a(slice(3,7,2), slice(1,11,2))
只是解釋器在[]
搜索start:stop:step
實例,並將它們slice(start, stop, step)
? 文檔簡單地說:
括號(下標)表示法在內部使用切片對象
這是我不能改變行為的python內部位之一嗎? 是否有可能使其他函數采用切片對象使用start:stop:step
速記?*
*我已經看到了另一個問題, 可以在括號外使用python的切片表示法嗎? ,但這只是使用自定義類,我可以輕松做到。 我想要的是一種只使用start:stop:step
而不必將其包裝在其他任何東西中。
邊注:
它也表明[...]
內的所有參數都被打包成一個tuple
,就好像它正在做[*args]
- > __getitem__(args)
。
class ExampleClass2(object):
def __getitem__(self, arg):
return arg
def __call__(self, arg):
return arg
b = ExampleClass2()
print b["argument 1", 2:4:6,3] # ('argument 1', slice(2, 4, 6), 3)
print b(slice(3,7,2), slice(1,11,2)) # TypeError: __call__() takes exactly 2 arguments (3 given)
Python語法定義何時可以使用切片運算符:
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
test
幾乎是任何表達式,但它只能在子subscriptlist
中使用切片運算符。 所以是的, 用於下標的方括號是重要的,但是用於列表的方括號不會神奇地允許你寫一個切片,也不能將切片放在恰好位於下標內的任意表達式中。
如果你想要切片,當你沒有訂閱東西時,你必須寫slice(a,b,c)
。
np.lib.index_tricks
包含幾個接受this ::
inputs的'函數',例如np.mgrid
, np.r_
, np.s_
。
它們實際上是作為類的實例實現的,具有__getitem__
定義。 他們被括號“稱為”。
np.s_[2::2] # slice(2, None, 2)
np.r_[-1:1:6j, [0]*3, 5, 6] # array([-1. , -0.6, -0.2, 0.2, ... 6. ])
mgrid[0:5,0:5]
我通常不會使用它們,但它們是如何利用__getitem__
一個有趣例子。
np.insert
是一個生成包含切片的索引元組的函數示例。 np.apply_along
還:
i = zeros(nd, 'O')
...
i[axis] = slice(None, None)
...
i.put(indlist, ind)
...arr[tuple(i.tolist())]
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html有相關說明:
請記住,切片元組總是可以構造為
obj
並在x[obj]
表示法中使用。 可以在構造中使用切片對象代替[start:stop:step]
表示法。 例如,x[1:10:5,::-1]
也可以實現為obj = (slice(1,10,5), slice(None,None,-1)); x[obj]
obj = (slice(1,10,5), slice(None,None,-1)); x[obj]
。 這對於構造適用於任意維數組的通用代碼非常有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.