此类如何实现"

编程入门 行业动态 更新时间:2024-10-05 01:24:09
本文介绍了此类如何实现"__iter__"没有实现“下一个"的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在django.template中有以下代码:

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)

下面让我感到困惑的部分.此__iter__方法如何工作?我找不到任何对应的next方法.

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

这是我知道如何实现__iter__的唯一方法:

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, please try to use code examples rather than text, because my English is not very good. Thank you.

推荐答案

来自 docs :

如果容器对象的__iter__() 方法被实现为生成器, 它将自动返回一个 迭代器对象(从技术上讲, 生成器对象)提供 __iter__()和__next__()方法.

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)

更多推荐

此类如何实现"

本文发布于:2023-11-28 04:23:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:此类   如何实现   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!