Iterator Objects: __iter__ and __next__

Although the __getitem__ technique of the prior section works, it’s really just a fallback for iteration. Today, all iteration contexts in Python will try the __iter__ method first, before trying __getitem__. That is, they prefer the iteration protocol we learned about in Chapter 14 to repeatedly indexing an object; only if the object does not support the iteration protocol is indexing attempted instead. Generally speaking, you should prefer __iter__ too—it supports general iteration contexts better than __getitem__ can.

Technically, iteration contexts work by calling the iter built-in function to try to find an __iter__ method, which is expected to return an iterator object. If it’s provided, Python then repeatedly calls this iterator object’s __next__ method to produce items until a StopIteration exception is raised. If no such __iter__ method is found, Python falls back on the __getitem__ scheme and repeatedly indexes by offsets as before, until an IndexError exception is raised. A next built-in function is also available as a convenience for manual iterations: next(I) is the same as I.__next__().

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元


Note

Version skew note: As described in Chapter 14, if you are using Python 2.6, the I.__next__() method just described is named I.next() in your Python, and the next(I) built-in is present for portability: it calls I.next() in 2.6 and I.__next__() in 3.0. Iteration works the same in 2.6 in all other respects.