python学习日记:day11----装饰器进阶
1、wraps
from functools import wraps def wrapper(func): #func = holiday @wraps(func)#输出holiday的函数名 def inner(*args,**kwargs): print('在被装饰的函数执行之前做的事') ret = func(*args,**kwargs) print('在被装饰的函数执行之后做的事') return ret return inner @wrapper #holiday = wrapper(holiday) def holiday(day): '''这是一个放假通知''' print('全体放假%s天'%day) return '好开心' print(holiday.__name__) print(holiday.__doc__) ret = holiday(3) #inner print(ret) # def wahaha(): # ''' # 一个打印娃哈哈的函数 # :return: # ''' # print('娃哈哈') # print(wahaha.__name__) #查看字符串格式的函数名 # print(wahaha.__doc__) #document。查看函数的注释内容wraps
2、带参数的装饰器
import time flag = True 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)#----》# timmer = timmer_out(FLAGE)----> #func1 = timmer(func1) def func1(): time.time(0.1) print('哇哈哈哈')带装饰器的函数
3,多个装饰器装饰一个函数
def wrapper1(func): def inner1(): print('wrapper1 ,before func') ret = func() print('wrapper1 ,after func') return ret return inner1 def wrapper2(func): def inner2(): print('wrapper2 ,before func') ret = func() print('wrapper2 ,after func') return ret return inner2 def wrapper3(func): def inner3(): print('wrapper3 ,before func') ret = func() print('wrapper3 ,after func') return ret return inner3 @wrapper3 @wrapper2 @wrapper1 def f(): print('in f') return '哈哈哈' print(f())多个装饰器装饰一个函数
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16