>>> def func():
... print("abc")
...
>>> func()
abc
>>> f = func
>>> f()
abc
>>> id(func) - id(f)
0
>>> f.__name__
'func'
>>>
>>> import time
>>> def print_date(f):
... def wrapper(*args, **kwargs):
... t = time.strftime("%Y-%m-%d", time.localtime())
... print(f"Date: {t}")
... return f(*args, **kwargs)
... return wrapper
...
>>>
>>> @print_date
... def func():
... print("abc")
...
>>> func()
Date: 2019-12-20
abc
>>>
>>> def manual():
... print("manual operation")
...
>>> func1 = print_date(manual)
>>> func1()
Date: 2019-12-20
manual operation
>>>
print_date
中的 def wrapper(*args, **kwargs)
那么标准>>> def cal_time(f):
... def wrapper(x, y):
... start = time.perf_counter_ns()
... f(x, y)
... stop = time.perf_counter_ns()
... print(f"run time: {stop - start}")
... return wrapper
...
>>> @cal_time
... def add_two_nums(x, y):
... print(f"{x} + {y} = {x + y}")
...
>>> add_two_nums(10, 20)
10 + 20 = 30
run time: 1606600
>>>
>>> def deco1(f):
... print("decorator1")
... def wrapper():
... print("decorator1's wrapper")
... f()
... return wrapper
...
>>> def deco2(f):
... print("decorator2")
... def wrapper():
... print("decorator2's wrapper")
... f()
... return wrapper
...
>>> @deco2
... @deco1
... def dbl_decos():
... print("double decorators")
...
decorator1
decorator2
>>> dbl_decos()
decorator2's wrapper
decorator1's wrapper
double decorators
>>>
def deco1(f):
print("先穿衬衫")
def wrapper():
print("再脱衬衫")
f()
return wrapper
def deco2(f):
print("再穿西装")
def wrapper():
print("先脱西装")
f()
return wrapper
@deco2
@deco1
def dbl_decos():
print("over")
if __name__ == "__main__":
dbl_decos()
>>>
先穿衬衫
再穿西装
先脱西装
再脱衬衫
over
原文:https://www.cnblogs.com/yorkyu/p/12078084.html