import time # 裝飾器函式 def log_cat(flag='false'): # 加一層可以進行引數傳遞 def time_def(f): def inner(*args): start = time.time() f(*args) end = time.time() s_e = end - start print("時間:%s" % s_e) if flag == "True": pass return inner return time_def @log_cat("True") # 等價於 @time_def @time_def 等價於 foo = time_def(foo) def add(*args): sum_args = sum(args) print(sum_args) time.sleep(1) add(1, 3, 5, 6, 9) # 已原來的方式呼叫,不改變呼叫方式 @log_cat() def foo(): print("foo1....") time.sleep(3) foo()