這篇文章主要介紹了Python for循環與getitem的關系詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
一個類里面如果由__iter__for循環就是找它取,沒有的話就會找__getitem__
前面一筆看過沒有留心具體的執行情況。
In [169]: class Foo: ...: def __getitem__(self, pos): ...: print(pos) ...: return range(10)[pos] ...:
In [172]: for i in f: ...: ... ...: ...: 012345678910
從代碼可以看出,如果沒有報錯或者設置顯式的條件,這個for循環會無線循環。
我現在設置一個顯式的設置。
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: ...: ... ...: 012345
將錯誤設置為IndexError也可以執行,但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: ...: ... ...: 012345
如果用list去運行這個參數會把返回的一個一個元素,裝入列表當中:
In [184]: list(f) 012345Out[184]: [0, 1, 2, 3, 4, 5]
只有__getitem__的類的實例是屬于可迭代對象,但用isinstances測試collections.Iterable是不能通過的,書后面介紹可以通過iter函數來測試,如果沒報錯就說明是可迭代對象,然后生成一個沒有__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__']
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網之家。
新聞熱點
疑難解答