Why did Python 2.6 add a global next() function?

自闭症网瘾萝莉.ら 提交于 2019-12-03 18:01:16

问题


I noticed that Python2.6 added a next() to it's list of global functions.

next(iterator[, default])

Retrieve the next item from the iterator by calling its next() method.

If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

What was the motivation for adding this? What can you do with next(iterator) that you can't do with iterator.next() and an except clause to handle the StopIteration?


回答1:


It's just for consistency with functions like len(). I believe next(i) calls i.__next__() internally.

See http://www.python.org/dev/peps/pep-3114/




回答2:


Note that in Python 3.0+ the next method has been renamed to __next__. This is because of consistency. next is a special method and special methods are named by convention (PEP 8) with double leading and trailing underscore. Special methods are not meant to be called directly, that's why the next built in function was introduced.




回答3:


It calls __next__ internally, but it makes it look more 'functional' than 'object-oriented'. Mind you that's just my opinion, but I don't like next(i) rather than i.next(). But as Steve Mc said, it also helps slightly with consistency.



来源:https://stackoverflow.com/questions/656155/why-did-python-2-6-add-a-global-next-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!