def log(text=None): def decorator(func): @functools.wraps(func) def wrapper(*args,**kw): if callable(text): print ('call %s():'%func.__name__) else: print ('%s %s():'%(text,func.__name__)) return func(*args,**kw) return wrapper return decorator(text) if callable(text) else decorator @log('excute') #decorator_1 def test4(i,j): return i*j @log #decorator_2 def test5(m,n): return m+n
1, decorator_1 execution process:
test4 = log('excute')(test4)
Step 1: Execute log('execute') execute is incallable return decorator
Step 2: Execute decorator(test4) to return wrapper, ie test4 = wrapper
Step 3: When calling test4, call wrapper to print print ('%s %s():'%(text,func.__name__)) and return to execute the original function test4
2.decorator_2 execution process:
test5 = log (test5)
Step 1: Execute log(test5), test5 is callable return decorator(test5)
Step 2: Execute decorator(test5), return wrapper, ie test5 = wrapper
Step 3: When calling test5, call wrapper to print print ('call %s():'%func.__name__) and return to execute the original function test5