import functools # 在代碼運行期間動態增加功能的方式,稱之爲“裝飾器”,裝飾器就是返回函數的高階函數 # 不帶參數的裝飾器 def log1(func): # 修正裝飾器的name指向 @functools.wraps(func) def wrapper(*args, **kw): print(func.__name__, '我要插入一個日誌') return func(*args, **kw) return wrapper # 帶參數的裝飾器 中間再加一層函數包裹 def log2(str): def d(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (str, func.__name__)) return func(*args, **kw) return wrapper return d def log3(str): def d(func): # @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (str, func.__name__)) return func(*args, **kw) return wrapper return d # 相當於 log1(hello1) @log1 def hello1(): print('hello world1') # 相當於log2(111)(hello2) @log2('111') def hello2(): print('hello world2') @log3('222') def hello3(): print('hello world3') hello1() # 裝飾器打印hello1 我要插入一個日誌 函數本身打印hello world1 print(hello1.__name__) print(hello2.__name__) # hello2 print(hello3.__name__) # wrapper 因爲沒有 @functools.wraps(func)修改指向