python control flow

fluent python control flow 这几章学习笔记:

第14章

1.

Iterable 包含一个__iter__方法,该方法返回一个iterator

iterator 包含一个__next__方法和一个__iter__方法,__iter__方法返回自己

所以:

任何iterator都是iterable

2. generator 不建议使用yield作为表达式使用,而是单纯的使用yield value,这样generator使用过程中不停使用next,直到产生StopIteration Exception

generator 和 普通的iterable的区别在于:

级联使用的时候,一个是pull,一个是push(参见David Beazly  的trilogy中的第二部所讲)

第15章

使用generator 作为 context manager

1. 使用generator 作为context manager 还是挺有意思的一种做法,

此时yield仍作为语句,yield 返回的value作为 with as 得到的值,在with 所包裹的语句中可以使用,

yield以后的语句作为清理现场的语句

第16章

讲述cotine 与 yield from 等等  这些python 提供的基础语法的使用

1. 这一章主要理解 使用 yield from 形成 coroutine 之间 任务的delegate 和  结果的返回

(就是理解 如何 在 coroutine 中使用 yield from 调用另外一个 coroutine)

理解控制流  caller  --->  delegating coroutine ---> subgenerator 

(这就是 David Beazly 所讲的蹦床理论,

caller 的值 传递给 subgenerator, subgenerator yield 之后,程序并不返回delegating coroutine执行, 而是 返回calller执行

只有subgenerator return之后(也就是raise StopIteration),程序返回delegating coroutine 执行

第17 章

1. 首先理解Future in python futures library

Future instance 就是 一段代码,这段代码已经绑定了一个 ThreadPoolExecutor or ProcessPoolExcutor, 这段代码一定会有一个 thread 或 process 去执行

2. 然后这一章使用 flag download 的 example

(1) 先是使用    for 循环 单线程 执行多个下载任务

(2)将   每个下载任务  使用 一个future 包裹,    然后丢到 Executor 去

第18 章

1. 首先 理解 Future in asyncio

 一个coroutine,绑定到一个loop中 ,  loop承诺执行   

2. Future  之于  asyncio 库

相当于 

Deferred  class  之于 Twisted

Future   class   之于  Tornado

3. python 中 使用 coroutine 作为 解决 单线程 异步编程问题,

JS使用 callback 和 更加抽象的 promise 作为解决方案

Node.js 使用 callback

4. 下载国旗  这个例子是

客户端使用  asyncio   +     aiohttp  实现  单线程 并发 HTTP 下载

5. server 端

使用 asyncio 提供的TCP API 实现 单线程 server  提供 telnet 服务

使用 asyncio + aiohttp 实现 单线程 提供 HTTP 服务

猜你喜欢

转载自www.cnblogs.com/eeechoo/p/9010213.html