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

后端 未结 2 1299
忘掉有多难
忘掉有多难 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: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)
    

提交回复
热议问题