看下面的示例:
a = [1, 2, 3, 4]
for i in a:
print(a)
a
是列表(可迭代)而不是迭代器。
我不是想知道
__iter__
或 iter()
将列表转换为迭代器!
我想知道 for 循环本身是否隐式转换列表,然后调用
__iter__
进行迭代保留列表而不删除类似的迭代器?
由于 stackoverflow 发现我的问题可能重复: 独特之处在于,我不是问 for 循环作为概念,也不是
__iter__
,我问的是 for 循环的核心机制以及与 iter 的关系。
我想知道 for 循环本身是否隐式转换列表,然后调用 iter 进行迭代保留列表而不删除类似的迭代器?
for
循环不会隐式转换列表,因为它会改变列表,但它隐式地从列表创建一个迭代器。列表本身在迭代过程中不会改变状态,但创建的迭代器会改变状态。
a = [1, 2, 3]
for x in a:
print(x)
相当于
a = [1, 2, 3]
it = iter(a) # calls a.__iter__
while True:
try:
x = next(it)
except StopIteration:
break
print(x)
这是
__iter__
实际上被调用的证据:
import random
class DemoIterable(object):
def __iter__(self):
print('__iter__ called')
return DemoIterator()
class DemoIterator(object):
def __next__(self):
print('__next__ called')
r = random.randint(1, 10)
if r == 5:
print('raising StopIteration')
raise StopIteration
return r
迭代
DemoIterable
:
>>> di = DemoIterable()
>>> for x in di:
... print(x)
...
__iter__ called
__next__ called
9
__next__ called
8
__next__ called
10
__next__ called
3
__next__ called
10
__next__ called
raising StopIteration