简体   繁体   English

这个类如何在不实现“next”的情况下实现“__iter__”方法?

[英]How does this class implement the "__iter__" method without implementing "next"?

I have the following code in django.template:我在 django.template 中有以下代码:

class Template(object):
    def __init__(self, template_string, origin=None, name='<Unknown Template>'):
        try:
            template_string = smart_unicode(template_string)
        except UnicodeDecodeError:
            raise TemplateEncodingError("Templates can only be constructed from unicode or UTF-8 strings.")
        if settings.TEMPLATE_DEBUG and origin is None:
            origin = StringOrigin(template_string)
        self.nodelist = compile_string(template_string, origin)
        self.name = name

    def __iter__(self):
        for node in self.nodelist:
            for subnode in node:
                yield subnode

    def render(self, context):
        "Display stage -- can be called many times"
        return self.nodelist.render(context)

The part I am confused about is below.我感到困惑的部分如下。 How does this __iter__ method work?这个__iter__方法是如何工作的? I can't find any corresponding next method.我找不到任何相应的next方法。

def __iter__(self):
        for node in self.nodelist:
            for subnode in node:
                yield subnode

This is the only way that I know how to implement __iter__ :这是我知道如何实现__iter__的唯一方法:

class a(object):
    def __init__(self,x=10):
        self.x = x
    def __iter__(self):
        return self
    def next(self):
        if self.x > 0:
            self.x-=1
            return self.x
        else:
            raise StopIteration
 ainst = a()
 for item in aisnt:
     print item

In your answers, try to use code examples rather than text, because my English is not very good.在你的回答中,尽量使用代码示例而不是文本,因为我的英语不是很好。

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.如果容器对象的__iter__()方法被实现为生成器,它将自动返回一个迭代器对象(技术上,一个生成器对象)提供__iter__()__next__()方法。

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)

That __iter__ method returns a python generator (see the documentation ), as it uses the yield keyword. __iter__方法返回一个 python生成器(请参阅文档),因为它使用了yield关键字。 The generator will provide the next() method automatically;生成器会自动提供 next() 方法; quoting the documentation:引用文档:

What makes generators so compact is that the __iter__() and next() methods are created automatically.生成器如此紧凑的原因是 __iter__() 和 next() 方法是自动创建的。

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 .这里有更多关于StackOverflow迭代器和生成器的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM