zjm*_*126 21 python iterator yield
我在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)
Run Code Online (Sandbox Code Playgroud)
我困惑的部分如下.这种__iter__
方法有什么用?我找不到任何相应的next
方法.
def __iter__(self):
for node in self.nodelist:
for subnode in node:
yield subnode
Run Code Online (Sandbox Code Playgroud)
这是我知道如何实现的唯一方法__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
Run Code Online (Sandbox Code Playgroud)
在你的答案中,请尝试使用代码示例而不是文本,因为我的英语不是很好.谢谢.
cat*_*try 15
该__iter__
方法返回一个python 生成器(请参阅文档),因为它使用yield
关键字.生成器将自动提供next()方法; 引用文档:
使生成器如此紧凑的原因是__iter __()和next()方法是自动创建的.
编辑:
生成器非常有用.如果您不熟悉它们,我建议您阅读它们,并使用一些测试代码.
以下是有关StackOverflow的迭代器和生成器的更多信息.