您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Python中for循環(huán)與getitem的關(guān)系是什么,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
一個(gè)類里面如果由__iter__for循環(huán)就是找它取,沒有的話就會(huì)找__getitem__
前面一筆看過沒有留心具體的執(zhí)行情況。
In [169]: class Foo: ...: def __getitem__(self, pos): ...: print(pos) ...: return range(10)[pos] ...:
In [172]: for i in f: ...: ... ...: ...: 0 1 2 3 4 5 6 7 8 9 10
從代碼可以看出,如果沒有報(bào)錯(cuò)或者設(shè)置顯式的條件,這個(gè)for循環(huán)會(huì)無線循環(huán)。
我現(xiàn)在設(shè)置一個(gè)顯式的設(shè)置。
In [173]: class Foo: ...: def __getitem__(self, pos): ...: if pos >5: ...: raise StopIteration ...: print(pos) ...: return range(10)[pos] ...:
In [177]: for i in f: ...: ... ...: 0 1 2 3 4 5
將錯(cuò)誤設(shè)置為IndexError也可以執(zhí)行,但TypeError就不行了。
...: def __getitem__(self, pos): ...: if pos >5: ...: raise IndexError ...: print(pos) ...: return range(10)[pos] ...: In [182]: In [182]: f = Foo() In [183]: for i in f: ...: ... ...: 0 1 2 3 4 5
如果用list去運(yùn)行這個(gè)參數(shù)會(huì)把返回的一個(gè)一個(gè)元素,裝入列表當(dāng)中:
In [184]: list(f) 0 1 2 3 4 5 Out[184]: [0, 1, 2, 3, 4, 5]
只有__getitem__的類的實(shí)例是屬于可迭代對(duì)象,但用isinstances測試collections.Iterable是不能通過的,書后面介紹可以通過iter函數(shù)來測試,如果沒報(bào)錯(cuò)就說明是可迭代對(duì)象,然后生成一個(gè)沒有__next__屬性的迭代器。
In [185]: from collections import Iterable In [186]: isinstance(f, Iterable) Out[186]: False In [187]: iter(f) Out[187]: <iterator at 0x114f2be50>
dir(f) Out[189]: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
看完上述內(nèi)容,你們對(duì)Python中for循環(huán)與getitem的關(guān)系是什么有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。