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版)
迭代器、生成器和经典协程
467
除了
__iter__
方法之外,你可能还想在
Sentence
类中实现
__next__
方法,让
Sentence
实例既是可迭代对象,也是自身的迭代器。可是,这种想法非常糟糕。
Alex Martelli
Google
有大量
Python
代码审查经验,他指出,这也是常见的反模式。
《设计模式》一书讲解迭代器设计模式时,在“适用性”一节中说:
迭代器模式可用来:
访问一个聚合对象的内容而无须暴露它的内部表示;
支持对聚合对象的多种遍历;
为遍历不同的聚合结构提供一个统一的接口(即支持多态迭代)。
为了“支持多种遍历”,必须能从同一个可迭代对象中获取多个独立的迭代器,而且各个
迭代器要能维护自身的内部状态。因此这一模式正确的实现方式是,每次调用
iter(my_
iterable)
都新建一个独立的迭代器。这就是本例需要
SentenceIterator
类的原因。
至此,我们演示了如何正确实现经典迭代器模式。现在,把本节内容忘掉。
Python
Barbara Liskov
发明的
CLU
语言中借鉴了
yield
关键字,因此我们无须自己动手编写实现
迭代器的代码。
17.5.3
节将展示如何使用更地道的方式实现
Sentence
类。
17.5.3
 
Sentence
类第
3
生成器函数
实现相同功能,但符合
Python
习惯的方式是,用生成器代替
SentenceIterator
类。先看
示例
17-5
,然后详细说明生成器。
示例
17-5
sentence_gen.py
:使用生成器实现
Sentence ...
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