1,不带参数的装饰器
def decorator(f)
def inner(*args, **kwargs)
'''扩展功能'''
innerVar = f(*args, **kwargs)
'''扩展功能'''
return innerVar
return inner
@decorator
def func(*args, **kwargs):
result = '''执行一些功能'''
return result
func()
调用过程
2,带参数的装饰器
def xxx(*args):
def wraper(func):
def inner(*args, **kwargs):
ret = func(*args, **kwargs)
return ret
return inner
return wraper
import time
def timer(judgementBit):
def wraper(func):
def inner(*args, **kwargs):
startTime = time.time()
ret = func(*args, **kwargs)
if judgementBit:
print(f'函数{func.__name__}执行时间为{time.time()-startTime}')
return ret
return inner
return wraper
@timer(True)
def func1():
time.sleep(1)
print('执行func1')
@timer(False)
def func2():
time.sleep(1)
print('执行func2')
func1()
func2()