[Python] for循環是怎樣工做的?

若是你從迭代層面來理解的話可能對於for的工做原理會有更深的理解。
首先咱們來使用dir查看一下對於range、str這兩個的不同的類型有什麼共同點。git

>>> dir(range)
['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',   
'__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__',   
'__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',   
'__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',   
'count', 'index', 'start', 'step', 'stop']  

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',   
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',   
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map',
 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 
'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
 'translate', 'upper', 'zfill']

查看這兩個的共有屬性

>>> set(dir(range)) & set(dir(str))
{'__hash__', '__eq__', '__contains__', '__iter__', '__getitem__', 'count', '__lt__', 
'__dir__', '__le__', '__subclasshook__', '__ge__', '__sizeof__', '__format__', '__len__', 
'__ne__', '__getattribute__', '__delattr__', '__reduce_ex__', '__gt__', '__reduce__', 
'__setattr__', '__doc__', '__class__', '__new__', '__repr__', '__init__', 'index', '__str__'}

咱們關注__iter__屬性,他們兩個都有這個函數,若是你查看其餘能夠使用for循環迭代的對象,你均可以發現這個特殊方法。
實現了這個方法的對象咱們稱之爲iterable。
咱們把對象傳給Python內置的iter()方法,會返回一個迭代器,for循環就是使用這個模式來實現適用於全部的對象。
好比:api

>>> iter([1, 2])
<list_iterator object at 0x000001A1141E0668>
>>> iter(range(0, 10))
<range_iterator object at 0x000001A1124C6BB0>
>>> iter("abc")
<str_iterator object at 0x000001A1141E0CF8>
>>>
iter函數返回的對象咱們稱之爲iterator,iterator只須要作一件事,那就是調用next(iterator)方法,返回下一個元素。

舉例:ssh

>>> t = iter("abc")
>>> next(t)
'a'
>>> next(t)
'b'
>>> next(t)
'c'
>>> next(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

當迭代器再沒有元素能夠迭代時會引起一個異常。
那麼在這裏我給出itrable和iterator的定義。
iterable:
能夠傳給iter並返回一個iteratot的對象
iterator:
能夠傳給next函數並返回下一個迭代元素的對象,並在迭代結束引起一個異常。ide

所以,對於你提的例子咱們使用迭代器來從新定義一下。函數

>>> t = iter(range(90, 0, -1))
>>> t
<range_iterator object at 0x000001A1124C6BB0>
>>> next(t)
90
>>> next(t)
89
>>> next(t)
88

但願看完有所收穫。spa

相關文章
相關標籤/搜索