How does this class implement the “__iter__” method without implementing “next”?

早过忘川 提交于 2019-12-02 17:13:29

From the docs:

If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() methods.

catchmeifyoutry

That __iter__method returns a python generator (see the documentation), as it uses the yield keyword. The generator will provide the next() method automatically; quoting the documentation:

What makes generators so compact is that the __iter__() and next() methods are created automatically.

EDIT:

Generators are really useful. If you are not familiar with them, I suggest you readup on them, and play around with some test code.

Here is some more info on iterators and generators from StackOverflow.

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