天天看點

Python進階: 通過執行個體詳解裝飾器(附代碼)

Python中的裝飾器有很多用處,比如輸出日志、參數檢查、代理設定、計數計時、結果緩存等等。本文就通過幾個裝飾器例子,詳細解釋一下Python中裝飾器的用法。

  • 一步步從簡到繁學習裝飾器用法
  • 其他一些裝飾器執行個體
  • Python中自帶的裝飾器

按照慣例,先上代碼:GitHub - xianhu/LearnPython: 以撸代碼的形式學習Python

(1)最簡單的裝飾器,實作日志輸出功能:

# 建構裝飾器
def logging(func):
    @functools.wraps(func)
    def decorator():
        print("%s called" % func.__name__)
        result = func()
        print("%s end" % func.__name__)
        return result
    return decorator

# 使用裝飾器
@logging
def test01():
    return 1

# 測試用例
print(test01())
print(test01.__name__)
           

代碼很簡單,很容易看懂。這裡注意"functools.wraps"用法,其目的是"test01.__name__"輸出正确的"test01"。"@logging"相當于"test01 = logging(test01)",傳回的是decorator函數,是以如果不加"functools.wraps",則"test01.__name__"傳回為"decorator"。

# 建構裝飾器
def logging(func):
    @functools.wraps(func)
    def decorator(a, b):
        print("%s called" % func.__name__)
        result = func(a, b)
        print("%s end" % func.__name__)
        return result
    return decorator

# 使用裝飾器
@logging
def test01(a, b):
    print("in function test01, a=%s, b=%s" % (a, b))
    return 1

# 測試用例
print(test01(1, 2))
           
# 建構裝飾器
def logging(func):
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        print("%s called" % func.__name__)
        result = func(*args, **kwargs)
        print("%s end" % func.__name__)
        return result
    return decorator

# 使用裝飾器
@logging
def test01(a, b):
    print("in function test01, a=%s, b=%s" % (a, b))
    return 1

# 使用裝飾器
@logging
def test02(a, b, c=1):
    print("in function test02, a=%s, b=%s, c=%s" % (a, b, c))
    return 1

# 測試用例
print(test01(1, 2))
print(test02(1, 2, c=3, d