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

后端 未结 2 1282
忘掉有多难
忘掉有多难 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.

    0 讨论(0)
  • 2021-01-31 05:22

    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.

    Here is your provided example using a generator:

    class A():
        def __init__(self, x=10):
            self.x = x
        def __iter__(self):
            for i in reversed(range(self.x)):
                yield i
    
    a = A()
    for item in a:
        print(item)
    
    0 讨论(0)
提交回复
热议问题