学python看到生成器函数
最先接触生成器函数是在js中,虽然python中很早就有了(明明是我先)。
js中generator函数介绍
js中generator函数常作为一种异步编程方式,作为传统回调函数的一种代替方式,使得我们可以以同步的方式编写异步代码。
以文件复制操作作为一个例子,先读取一个文件的内容,再把内容写入到另一个文件。
首先创建一个1.txt文件
1 echo "hello,world" >> 1.txt
代码
copy file 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 let fs = require ("fs" );function generator (gen ) { let g = gen(); let next = function (value ) { let result = g.next(value); if (!result.done) { result.value(next); } } next(); } function readFile (url ) { return function (next ) { fs.readFile(url,"utf8" , (err, data) => { if (err) { throw err; } next(data); }); } } function writeFile (path, data ) { return function (next ) { fs.writeFile(path, data, "utf8" , (err) => { if (err) { throw err; } next(); }); } } generator(function * ( ) { let data = yield readFile("1.txt" ); console .log("read 1.txt:" , data); let result = yield writeFile("2.txt" , data); console .log("2.txt created" ); }) console .log("next step" );
在generator函数中虽然readFile和writeFile都是异步操作,但是写起来是同步的逻辑,并且不会阻塞下面的操作,next step会先被打印出来。
生成器函数定义了next方法,是支持迭代的
pyhton 3.6 斐波那契数列 1 2 3 4 5 6 7 8 9 10 def fibon (n) : a = b = 1 for i in range(n): yield a a, b = b, a + b for x in fibon(100 ): print(x)
js中也可以用for of进行迭代
而且相比较list,array等支持迭代的类型,generator函数占用的内存会小得多