[note]how a generator works
来源:互联网 发布:网络教育一年多少钱 编辑:程序博客网 时间:2024/05/13 20:57
how a generator works
A Sentence class was discussed in the previous blog.
however, the versions of Sentence haven been created are not pythonic.
Let's see another version.
import re, reprlibRE_WORD = re.compile("\w+")class Sentence(object): def __init__(self, txt): self.words = RE_WORD.findall(txt) def __repr__(self): return "Sentence({})".format(reprlib.repr(self.words)) def __iter__(self): for ele in self.words: yield ele return # do not needthe return above is not needed. the function just fall thought and return automatically.
Either way, a generator function doesn't raise StopIteration Exception: it just exits when it's done producing values.
the __iter__ function above is a generator function, which return a generator and that is also an iterator.
what is a generator function?
any python function that has the yield keyword in its body is a generator function:a function which, when called, returns a generator object. In other words, a generator function is a generator factory.
for example:
def gen_123(): yield 1 yield 2 yield 3
>>> gen_123 # gen_123 is still a function object
<function gen_123 at 0x...>
>>> gen_123() # that is a generator now.
<generator object gen_123 at 0x...>
>>> for i in gen_123():
ptint(i)
1
2
3
>>> g = gen_123()
>>> next(g)
1
>>> next(g)
2
>>> next(g)
3
>>> next(g) # when generator is exhausted and applied next function, a StopIteration will be raised.
Traceback (most recent call last):
...
StopIteration
finally, when the function body returns, the enclosing generator object raises StopIteration, in accordance with the Iterator Protocol.
And the yield keyword in generator function suspends the process.
The following case will demonstrate it well.
>>> def gen_AB():
print("start...")
yield 'A'
print("continue")
yield 'B'
print("end")
>>> for c in gen_AB():
print('--->', c)
start...
---> A
continue
---> B
end
>>>
print("start...")
yield 'A'
print("continue")
yield 'B'
print("end")
>>> for c in gen_AB():
print('--->', c)
start...
---> A
continue
---> B
end
>>>
Obviously, the for loop machinery code catches the StopIteration Exception, and the loop terminates clearly.
So, the pythonic Sentence class is created:
class Sentence(object): def __init__(self, txt): self.txt = txt def __repr__(self): return "Sentence({})".format(reprlib.repr(self.text)) def __iter__(self): for match in RE_WORD.finditer(self.txt): yield match.group()the finditer method also return an Iterator, that saves more memory.
0 0
- [note]how a generator works
- How a CPU Works ?
- How a Server Cluster Works
- How A Servlet container Works
- How A Servlet container Works
- How a Perl5 program works
- Note 836243 - How condition exclusion works in R/3
- How a Regex Engine Works Internally
- 正则表达式学习指南(四)----How a Regex Engine Works Internally
- How Compressor Attack and Release Works? A Beginner Tutorial
- Thinking In Java 之 How a garbage collector works
- think in java笔记:How a garbage collector works
- How a Kalman filter works, in pictures (译文)
- How a Kalman filter works, in pictures | Bzarg
- How can I create a object for a note?
- How Internet EDI Works
- How E-mail Works
- How E-mail Works
- 【Android开发经验】来来来,同学,咱们讨论一下“只能在UI主线程更新View”这件小事
- 需要学习的内容,记录在这里,逐步更新!2015-12-26
- 神经网络反向传播公式的推导
- Android 自定义弹出框
- VC中获取窗口句柄的各种方法
- [note]how a generator works
- AS问题解决 Not recognizing known sRGB profile
- android读取联系人的两种方式
- Windows下的修改Tomcat的可用内存
- [错误整理]error LNK1123:转换到COFF期间失败 解决方案
- Makefile 使用总结
- asp读取数据库判断是否为空
- 记录kernel lcd驱动 register_framebuffer中的一个bug
- 在存储过程中实现分页.