1.套模板
def init(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) next(res) return res return wrapper
def init(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) next(res) return res return wrapper@init #eater=init(eater)def eater(name): print('%s start to eat' % name) food_list=[] while True: food = yield food_list print('%s eat %s' %(name,food)) food_list.append(food)e = eater('zhejiangF4') #wrapper('zhejiangF4')#e.send('123')print(e.send('123'))print(e.send('123'))print(e.send('123'))zhejiangF4 start to eatzhejiangF4 eat 123['123']zhejiangF4 eat 123['123', '123']zhejiangF4 eat 123['123', '123', '123']
2.作业1
1 ''' 2 文件名:a.txt,文件内容如下: 3 apple 10 3 4 tesla 100000 1 5 mac 3000 2 6 lenovo 30000 3 7 chicken 10 3 8 实现功能:cat a.txt|grep apple 9 要求1:实现迭代器函数cat10 要求2:定义迭代器函数grep11 要求3:模拟管道的功能,将cat的处理结果作为grep的输入12 # cat a.txt | grep apple13 # 定义迭代器cat14 # 定义迭代器grep15 # 模拟管道功能, 将cat的处理结果作为grep的输入16 '''17 def cat(file):18 with open(file) as f:19 for line in f:20 yield line.strip()21 22 def grep(keywords,lines):23 for line in lines:24 if keywords in line:25 yield line26 g1 = cat('b.txt')27 g2 = grep('apple',g1)28 for i in g2:29 print(i)
3.作业2
#!/usr/bin/env python3# -*- coding: utf-8 -*-# 生成器的应用, 将下面的函数改为协程函数, 用send来发送url# def get(url):# def index():# return urlopen(url).read()# return indexfrom urllib.request import urlopendef get(): while True: #while不断做这个事。做一个死循环. (如果没有while根据next传值send传值做几次) url=yield #初始化过了,从暂停位置开始走,把send里面的值传给它yield,把yield的值再给url,在往下执行res,再打印 res=urlopen(url).read() print(res)g=get()next(g) #初始化一下,让函数停在那个位置g.send('http://www.python.org')##爬网页