【__iter__】
如果一个类想被用于for ... in
循环,类似list或tuple那样,就必须实现一个__iter__()
方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的next()
方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。
我们以斐波那契数列为例,写一个Fib类,可以作用于for循环:
现在,试试把Fib实例作用于for循环:
container.
__iter__
()
Return an iterator object. The object is required to support the iterator protocol described below.
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
-
iterator.
__iter__
() -
Return the iterator object itself. This is required to allow both containers and iterators to be used with the
for
andin
statements.
-
iterator.
__next__
() -
Return the next item from the container. If there are no further items, raise the
StopIteration
exception.
参考:https://docs.python.org/3.5/library/stdtypes.html#typeiter