Advanced decorator
1, using a decorator function, but also through __name __, __ doc__ view to the calling function function name and comments
from functools Import Wraps DEF wrapper (FUNC): # FUNC = Holiday @wraps (FUNC) DEF Inner (* args, ** kwargs): Print ( ' before being decorated function performs do ' ) RET = FUNC (* args, ** kwargs) Print ( ' after being decorated function performs do ' ) return RET return Inner @wrapper # Holiday = wrapper (Holiday) DEF Holiday (Day): '' ' this is a holiday notice ' ' ' Print (' All the holiday% s days ' % Day) return ' good fun ' Print (Holiday. __Name__ ) # print out the calling function function name Print (Holiday. __Doc__ ) # print out the annotation function is called function # result: # Holiday # this is a holiday notice
# From functools Import Wraps DEF wrapper (FUNC): # FUNC = Holiday # @wraps (FUNC) DEF Inner (* args, ** kwargs): Print ( ' before the function is executed decorative doing ' ) RET = FUNC (* args, ** kwargs) Print ( ' after the function execution garnished do ' ) return RET return Inner @wrapper # Holiday = wrapper (Holiday) DEF Holiday (Day): '' ' this is a holiday notice '' ' Print ( 'All-day holiday% s ' % Day) return ' good fun ' Print (Holiday. __Name__ ) # print out the name of the function calls the function Print (Holiday. __Doc__ ) # print out the comments function call function # the first row and three lines of code removed, the result # Inner # None
2, with parameters decorator
If you need to use a decorator function for some time, but after this time it does not have the time, you can use parameterized decorator
import time FLAGE = False 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 = timmer_out(FLAGE) @timmer_out(FLAGE) #wahaha = timmer(wahaha) def wahaha(): time.sleep(0.1) print('wahahahahahaha') @timmer_out(FLAGE) def erguotou(): time.sleep(0.1) print('erguotoutoutou') wahaha() erguotou()
3, a plurality of decorative function decorator
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())