Skip to Content
流畅的Python(第2版)
book

流畅的Python(第2版)

by Luciano Ramalho
April 2023
Intermediate to advanced
769 pages
25h 16m
Chinese
Posts & Telecom Press
Content preview from 流畅的Python(第2版)
迭代器、生成器和经典协程
497
count += 1
average = total/count
这个函数返回一个生成器,该生成器产出
float
值,通过
.send()
接受
float
值,而且
不返回有用的值。
15
这个无限循环表明,只要客户代码不断发送值,它就会一直产出平均值。
这里的
yield
语句暂停执行协程,把结果发给客户,而且稍后还用于接收调用方后面发
给协程的值,再次开始无限循环迭代。
使用协程的好处是,
total
count
声明为局部变量即可,在协程暂停并等待下一次调
.send()
期间,无须使用实例属性或闭包保持上下文。正是这一点吸引人们在异步编程
中把回调换成协程,因为在多次激活之间,协程能保持局部状态。
示例
17-38
是使用
averager
协程的
doctest
示例
17-38
coroaverager.py
:示例
17-37
中定义的累计平均值协程的
doctest
>>> coro_avg = averager()
>>> next(coro_avg)
0.0
>>> coro_avg.send(10)
10.0
>>> coro_avg.send(30)
20.0
>>> coro_avg.send(5)
15.0
创建协程对象。
开始执行协程。这里产出
average
变量的初始值,即
0.0
真正计算累计平均值:多次调用
.send()
方法,产出当前平均值。
在示例
17-38
,调用
next(coro_avg)
后,协程向前执行到
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin
高效能PYTHON程式設計

高效能PYTHON程式設計

Micha Gorelick, Ian Ozsvald

Publisher Resources

ISBN: 9787115612366