Python 2.6+ 和 3.* 有 next(),但是 pre-2.6 只提供了 object.next 方法。有没有办法在 pre-2.6 中获得 next() 样式;也许是一些“def next():”结构?
最佳答案
class Throw(object): pass
throw = Throw() # easy sentinel hack
def next(iterator, default=throw):
"""next(iterator[, default])
Return the next item from the iterator. If default is given
and the iterator is exhausted, it is returned instead of
raising StopIteration.
"""
try:
iternext = iterator.next.__call__
# this way an AttributeError while executing next() isn't hidden
# (2.6 does this too)
except AttributeError:
raise TypeError("%s object is not an iterator" % type(iterator).__name__)
try:
return iternext()
except StopIteration:
if default is throw:
raise
return default
(throw = object()
也可以工作,但这会在检查时生成更好的文档,例如 help(next)
。None
不是合适,因为你必须区别对待 next(it)
和 next(it, None)
。)
关于python - def next() 适用于 Python pre-2.6? (而不是 object.next 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1716428/