什么是decorate?
python decorate 就是python 的一种高阶函数用法。
例子详解, 管中窥豹。
def decorate_func(func):
print("call decorate_func() here")
def wrapper(*args, **kwargs):
print(f"decorate_func- call wrapper and arguments are {args} + {kwargs}")
func(*args, **kwargs)
return wrapper
def timer_log(number):
print(f"call time_log({number}) function")
def decorate_func2(func):
print("call decorate_func2 here")
def wrapper(*args, **kwargs):
print(f"decorate_func2 - call wrapper and arguments are {args} + {kwargs}")
func(*args, **kwargs)
return wrapper
return decorate_func2
# the usage "@decorate_func()" is invalid. Error - TypeError: decorate_func() missing 1 required positional argument: 'func'
@decorate_func
def myfirstname(name):
print(f"I am {name}")
@timer_log(10)
def mylastname(name):
print(f"my last name is {name}")
myfirstname("Wu")
mylastname("Tom")
call decorate_func() here # 当python 解析到line 23, python 执行装饰器@decorate_func
call time_log(10) function # 当python 解析到line 27, python 先执行装饰器@timer_log(10),得到的返回值还是一个高阶函数decorate_func2
call decorate_func2 here # 再执行 decorate_func2
decorate_func- call wrapper and arguments are ('Wu',) + {} # 当代码执行到line31, myfirstname.__name__已经变成wrapper,所以执行 `myfirstname("Wu")` 就等于执行 wrapper 函数。
I am Wu
decorate_func2 - call wrapper and arguments are ('Tom',) + {}
my last name is Tom
Process finished with exit code 0