装饰器
装饰器的本质就是一个闭包函数
装饰器的功能:在不修改原函数及其调用方式的情况下对原函数功能进行扩展
# def wrapper(func): # def inner(*args,**kwargs):
''' 在函数执行前执行的操作 ''' # ret = func(*args,**kwargs)
''' 在函数执行后执行的操作 ''' # return ret # return inner # # @wrapper #语法糖 # def func(): # pass # func()
多个装饰器装饰一个函数
# def wrapper1(func): # def inner1(*args,**kwargs): # print('110011') # ret = func(*args,**kwargs) # print('001100') # return ret # return inner1 # # def wrapper2(func): # def inner2(*args,**kwargs): # print('220022') # ret = func(*args,**kwargs) # print('002200') # return ret # return inner2 # # def wrapper3(func): # def inner3(*args,**kwargs): # print('330033') # ret = func(*args,**kwargs) # print('003300') # return ret # return inner3 # # @wrapper3 # @wrapper2 # @wrapper1 # def f(): # print('in f') # # f()
执行结果如下:
330033
220022
110011
in f
001100
002200
003300
一个装饰器装饰多个函数,并用变量控制
# import time # FLAG = 1 #控制变量 FLAG 修改FLAG可让装饰器实现不同功能 # def timmer_out(flag): # def timmer(func): # def inner(*args,**kwargs): # if flag: # start = time.time() # ret = func(*args,**kwargs) # end = time.time() # print(end-start) # return ret # else: # ret = func(*args,**kwargs) # return ret # return inner # return timmer # # # @timmer_out(FLAG) # def shop_add(): # time.sleep(0.1) # print('添加一个') # @timmer_out(FLAG) # def shop_del(): # time.sleep(0.2) # print('减少一个') # # shop_add() # shop_add() # shop_del()
生成器
带yield的函数就是生成器
def wahaha(): for i in range(20): yield 'wahahha%s'%i w = wahaha() ret = w.__next__() print(ret)
从生成器中取值方法
next方法 for循环 强制类型转换
send方法
# def generator(): # print(123) # content = yield 1 # print('====',content) # print(456) # yield 2 # # g = generator() # ret = g.__next__() # print(ret) # ret = g.send('hello') # print(ret) send方法,获取下一个值时和next效果一样 #只是在获取下一个值时,给上一yield的位置传入一个数据 #第一次获取值时不能用send只能用next方法 #最后一个yield不能接收外部数据
#获取动态平均值
# def init(func):
# def inner(*args,**kwargs):
# g = func(*args,**kwargs)
# g.__next__()
# return g
# return inner #装饰器执行next方法 用户更方便
#
# @init
# def average():
# sum = 0
# avg = 0
# count = 0
# while True:
# num = yield avg
# sum += num
# count += 1
# avg = sum / count
#
# ag = average()
# ret = ag.send(10)
# print(ret)
# ret = ag.send(20)
# print(ret)
# ret = ag.send(30)
# print(ret)