预计阅读本页时间:-
Manual Iteration: iter and next
To support manual iteration code (with less typing), Python 3.0 also provides a built-in function, next, that automatically calls an object’s __next__ method. Given an iterable object X, the call next(X) is the same as X.__next__(), but noticeably simpler. With files, for instance, either form may be used:
>>> f = open('script1.py')
>>> f.__next__() # Call iteration method directly
'import sys\n'
>>> f.__next__()
'print(sys.path)\n'
>>> f = open('script1.py')
>>> next(f) # next built-in calls __next__
'import sys\n'
>>> next(f)
'print(sys.path)\n'
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Technically, there is one more piece to the iteration protocol. When the for loop begins, it obtains an iterator from the iterable object by passing it to the iter built-in function; the object returned by iter has the required next method. This becomes obvious if we look at how for loops internally process built-in sequence types such as lists:
>>> L = [1, 2, 3]
>>> I = iter(L) # Obtain an iterator object
>>> I.next() # Call next to advance to next item
1
>>> I.next()
2
>>> I.next()
3
>>> I.next()
Traceback (most recent call last):
...more omitted...
StopIteration
This initial step is not required for files, because a file object is its own iterator. That is, files have their own __next__ method and so do not need to return a different object that does:
>>> f = open('script1.py')
>>> iter(f) is f
True
>>> f.__next__()
'import sys\n'
Lists, and many other built-in objects, are not their own iterators because they support multiple open iterations. For such objects, we must call iter to start iterating:
>>> L = [1, 2, 3]
>>> iter(L) is L
False
>>> L.__next__()
AttributeError: 'list' object has no attribute '__next__'
>>> I = iter(L)
>>> I.__next__()
1
>>> next(I) # Same as I.__next__()
2
Although Python iteration tools call these functions automatically, we can use them to apply the iteration protocol manually, too. The following interaction demonstrates the equivalence between automatic and manual iteration:[34]
>>> L = [1, 2, 3]
>>>
>>> for X in L: # Automatic iteration
... print(X ** 2, end=' ') # Obtains iter, calls __next__, catches exceptions
...
1 4 9
>>> I = iter(L) # Manual iteration: what for loops usually do
>>> while True:
... try: # try statement catches exceptions
... X = next(I) # Or call I.__next__
... except StopIteration:
... break
... print(X ** 2, end=' ')
...
1 4 9
To understand this code, you need to know that try statements run an action and catch exceptions that occur while the action runs (we’ll explore exceptions in depth in Part VII). I should also note that for loops and other iteration contexts can sometimes work differently for user-defined classes, repeatedly indexing an object instead of running the iteration protocol. We’ll defer that story until we study class operator overloading in Chapter 29.
Note
Version skew note: In Python 2.6, the iteration method is named X.next() instead of X.__next__(). For portability, the next(X) built-in function is available in Python 2.6 too (but not earlier), and calls 2.6’s X.next() instead of 3.0’s X.__next__(). Iteration works the same in 2.6 in all other ways, though; simply use X.next() or next(X) for manual iterations, instead of 3.0’s X.__next__(). Prior to 2.6, use manual X.next() calls instead of next(X).