问题
In Python 2 iterators offer .next(), a callable method:
it = iter(xrange(10))
it.next()
> 0
it.next()
> 1
...
In Python 3 one has to use the built-in function next():
it = iter(range(10))
next(it)
> 0
next(it)
> 1
...
Is this just "syntactic sugar"? Like making it more obvious to use next() by moving it into the built-in functions? Or does any advanced concept hide behind this change?
回答1:
You are directly asking about PEP 3114
consider the following code:
class test:
def __iter__(self):
return self
def next(self):
return "next"
def __next__(self):
return "__next__"
x = test()
for i,thing in enumerate(x):
print(thing)
if i>4:
break
in python 2 next is printed but in python 3 __next__ is printed, since the method is being called implicitly it makes way more sense to match other implicit methods such as __add__ or __getitem__, which is described in the PEP.
If you are planning on using next explicitly then much like len, iter, getattr, hash etc. then python provides a built in function to call the implicit function for you. At least... after PEP 3114. 😀
Also, the next built-in allows you pass a default value if you don't want to throw an error if the iterable is finished which is frequently useful:
it = iter([])
x = next(it, "pls don't crash")
which couldn't really be standardized for a .next() method call. As well objects such as a random number generator may define a .next (next number) method without necessarily wanting to be an iterator which could have left ambiguity / confusion.
来源:https://stackoverflow.com/questions/36212812/python-2-someiterator-next-vs-nextsomeiterator-python-3