这个类如何实现“__iter__”?方法而不实现“next”?

发布于 2024-08-16 12:07:39 字数 1467 浏览 9 评论 0原文

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

在您的答案中,尝试使用代码示例而不是文本,因为我的英语不是很好。

I have the following code in 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? I can't find any corresponding next method.

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__:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ヤ经典坏疍 2024-08-23 12:07:39

来自 文档

如果容器对象的__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)

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)
樱娆 2024-08-23 12:07:39

__iter__ 方法返回一个 python generator (请参阅 文档),因为它使用 yield 关键字。
生成器会自动提供next()方法;引用文档:

生成器如此紧凑的原因是创建了 __iter__() 和 next() 方法
自动。

编辑:

生成器非常有用。如果您不熟悉它们,我建议您阅读它们,并尝试一些测试代码。

以下是来自 StackOverflow 的有关迭代器和生成器的更多信息。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文