簡體   English   中英

這個類如何在不實現“next”的情況下實現“__iter__”方法?

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

我在 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)

我感到困惑的部分如下。 這個__iter__方法是如何工作的? 我找不到任何相應的next方法。

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

這是我知道如何實現__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

在你的回答中,盡量使用代碼示例而不是文本,因為我的英語不是很好。

文檔

如果容器對象的__iter__()方法被實現為生成器,它將自動返回一個迭代器對象(技術上,一個生成器對象)提供__iter__()__next__()方法。

這是您提供的使用生成器的示例:

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)

__iter__方法返回一個 python生成器(請參閱文檔),因為它使用了yield關鍵字。 生成器會自動提供 next() 方法; 引用文檔:

生成器如此緊湊的原因是 __iter__() 和 next() 方法是自動創建的。

編輯:

發電機真的很有用。 如果您不熟悉它們,我建議您閱讀它們,並嘗試一些測試代碼。

這里有更多關於StackOverflow迭代器和生成器的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM