十、python開發之裝飾器
阿新 • • 發佈:2018-05-03
func 裝飾器 star def python開發 本質 添加 pro int 一、裝飾器:(decorator)
介紹:1、本質是函數,為其他函數添加附加功能。
2、不能修改被裝飾的函數的源代碼。
3、不能修改被裝飾的函數的調用方式。
定義:高階函數+嵌套函數==>裝飾器
二、定義一個函數並為其添加一個計時功能的裝飾器
import time
def func1(func):
def func2(*args):
start_time = time.time()
func(*args)
stop_time = time.time()
print("program run time %s" %(stop_time-start_time))
return func2
@func1
def func(*args):
print(*args)
time.sleep(5)
func(3,5,6,7,3)
三、裝飾器語法:
被裝飾函數的正上方,單獨一行
@func1
@func2
def func(*args):
print(*args)
time.sleep(5)
func(3,5,6,7,3)
十、python開發之裝飾器