kkpiece 2020-03-25
def deco1(func1): #func1 = wrapper2的内存地址 def wrapper(*args,**kwargs): print(‘正在运行======>deco1.wrapper1‘) res1 = func1(*args,**kwargs) # func1是wrapper2 return res1 return wrapper ? def deco2(func2): #func2 = wrapper3的内存地址 def wrapper2(*args,**kwargs): print(‘正在运行======>deco2.wrapper2‘) res2 = func2(*args,**kwargs) # func2是wrapper3 return res2 return wrapper2 ? def deco3(x): def outter3(func3): #func3 = 被装饰对象index的内存地址 def wrapper3(*args,**kwargs): print(‘正在运行======>deco2.wrapper3‘) res3 = func3(*args,**kwargs) # func3是index return res3 return wrapper3 return outter3 ? #加载顺序:自下而上(了解) ? @deco1 # deco1(wrapper2的内存地址) ===> index = wrapper1的内存地址 @deco2 # deco2(wrapper3的内存地址) ===> index = wrapper2的内存地址 @deco3(111) # ===> @outter3 ===> index = outter3(index) ===> index = wrapper3的内存地址 def index(x,y): print(‘from index %s:%s‘%(x,y)) ? index(1,2) ? #执行顺序:自上而下 即:wrapper1 ==> wrapper2 ==> wrapper3 #index(1,2) # wrapper1(1,2)
def dog(name): print(‘道哥%s准备吃东西了...‘ % name) while True: # x拿到的是yield接收到的值 x = yield # x = ‘一根骨头‘ print(‘道哥%s吃了 %s‘ % (name, x)) ? g = dog(‘alex‘) ? g.send(None) # 等同于next(g),先完成初始化 ? g.send(‘一根骨头‘) # g.send(‘一根骨头‘,‘肉包子‘) # 不能传2个值,会报错:TypeError: send() takes exactly one argument (2 given) g.send([‘一根骨头‘,‘肉包子‘]) # 可以放到列表里传输,列表算是一个值 g.send(‘肉包子‘) g.send(‘一桶泔水‘) # g.close() # g.send(‘1111‘) # 关闭之后无法传值
def dog(name): food_list = [] print(‘大哥%s准备吃东西了...‘ % name) while True: # x拿到的是yield接收到的值 # x = yield 111 # x = [‘一根骨头‘,‘肉包子‘] x = yield food_list # x = [‘一根骨头‘,‘肉包子‘] print(‘大哥%s抽了 %s‘ % (name, x)) food_list.append(x) ? g = dog(‘egon‘) ? res = g.send(None) # 等同于next(g),先完成初始化 print(res) ? res = g.send([‘一个鞭炮‘,‘一根烟‘]) print(res) ? res = g.send(‘一个地雷‘) print(res) def func(): print(‘start...‘) x = yield 111 print(‘H哈哈‘) print(‘H哈哈‘) print(‘H哈哈‘) yield 222 ? g = func() res = next(g) print(res) ? res = g.send(‘xxxx‘) print(res)