为什么 <for i in obj:> 和 <for i in iter(obj):> 等价?
Why are <for i in obj:> and <for i in iter(obj):> equivalent?
下面的例子是由documentation给出的:
In the statement for X in Y
, Y must be an iterator or some object for which iter()
can create an iterator. These two statements are equivalent:
for i in iter(obj):
print(i)
for i in obj:
print(i)
根据同样的 source,
Behind the scenes, the for statement calls iter()
on the container object. The function returns an iterator object that defines the method __next__()
which accesses elements in the container one at a time. When there are no more elements, __next__()
raises a StopIteration
exception which tells the for loop to terminate.
考虑到这两种情况,当 Y 是迭代器或 iter() 可以为其创建迭代器的某个对象时,
- 如果 Y 是一个可迭代对象(有一个
iter()
方法),for 语句调用这个方法并且 returns 一个迭代器 next()
方法用于遍历Y的每个元素。我假设这是上面的第二个例子。
- 如果 Y 是迭代器(同时具有
iter()
和 next()
方法),for 语句仍然调用 iter()
方法, 但因为它是一个迭代器,所以它 returns 它 self
,next()
方法照常被调用。我假设这是上面的第一个例子。
我的问题是,我的推理是否正确?我不介意您指出任何对定义的误用。
见https://docs.python.org/3/library/stdtypes.html#typeiter。
iterator.__iter__()
Return the iterator object itself. This is
required to allow both containers and iterators to be used with the
for and in statements. This method corresponds to the tp_iter slot of
the type structure for Python objects in the Python/C API.
下面的例子是由documentation给出的:
In the statement
for X in Y
, Y must be an iterator or some object for whichiter()
can create an iterator. These two statements are equivalent:for i in iter(obj): print(i) for i in obj: print(i)
根据同样的 source,
Behind the scenes, the for statement calls
iter()
on the container object. The function returns an iterator object that defines the method__next__()
which accesses elements in the container one at a time. When there are no more elements,__next__()
raises aStopIteration
exception which tells the for loop to terminate.
考虑到这两种情况,当 Y 是迭代器或 iter() 可以为其创建迭代器的某个对象时,
- 如果 Y 是一个可迭代对象(有一个
iter()
方法),for 语句调用这个方法并且 returns 一个迭代器next()
方法用于遍历Y的每个元素。我假设这是上面的第二个例子。 - 如果 Y 是迭代器(同时具有
iter()
和next()
方法),for 语句仍然调用iter()
方法, 但因为它是一个迭代器,所以它 returns 它self
,next()
方法照常被调用。我假设这是上面的第一个例子。
我的问题是,我的推理是否正确?我不介意您指出任何对定义的误用。
见https://docs.python.org/3/library/stdtypes.html#typeiter。
iterator.__iter__()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.