装饰器是给其他函数添加功能的函数,比如说要给函数添加计时功能
def 装饰器名(func):
def record_time():
start = time.time()
func()
end = time.time()
print(end-start)
return record_time
@装饰器名
def display():
代码块
display()
调用display函数时,程序会进入装饰器函数执行
若被添加的函数有返回值:
def 装饰器名(func):
def record_time():
start = time.time()
answer = func()
end = time.time()
print(end-start)
return answer
return record_time
@装饰器名
def display():
代码块
return 返回值
返回值 = display()
若被添加功能需要传入参数:
def 装饰器名(func):
def record_time(*args):
start = time.time()
func(*args)
end = time.time()
print(end-start)
return record_time
@装饰器名
def display(nums):
代码块
display(100)