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

后端 未结 2 1281
忘掉有多难
忘掉有多难 2021-01-31 04:28

I have the following code in django.template:

class Template(object):
    def __init__(self, template_string, origin=None, name=\'\'):
           


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 05:14

    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.

提交回复
热议问题