萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

Python 描述符協議深度解析:從類型檢查到只讀屬性的優雅實現

什麼是描述符?

描述符是實現了描述符協議的對象,即定義了 __get__、__set__、__delete__ 中任一或多個方法的類實例。它代表一個屬性的訪問邏輯,而非單純的值存儲。

  • 僅實現 __get__ → 非數據描述符(只讀)
  • 同時實現 __get__ + __set__ → 數據描述符(可讀寫)

描述符協議方法簽名

descr.__get__(self, obj, type=None) -> value
descr.__set__(self, obj, value) -> None
descr.__delete__(self, obj) -> None

場景一:優雅的屬性類型檢查

傳統 __init__ 手動檢查繁瑣且難復用。描述符方案:

class TypedProperty:
    def __init__(self, name, type_, default=None):
        self.name = '_' + name
        self.type = type_
        self.default = default if default is not None else type_()

    def __get__(self, instance, owner):
        return getattr(instance, self.name, self.default)

    def __set__(self, instance, value):
        if not isinstance(value, self.type):
            raise TypeError(f"Must be a {self.type.__name__}")
        setattr(instance, self.name, value)

    def __delete__(self, instance):
        raise AttributeError("Can't delete attribute")

class Foo:
    name = TypedProperty("name", str)
    num  = TypedProperty("num", int, 42)

f = Foo()
f.name = "obi"      # 通過
f.num = 1234        # 通過
f.num = "1234"      # TypeError: Must be an int

關鍵點:描述符必須定義在類屬性,不能在 __init__ 中動態創建。

屬性訪問解析優先級鏈

obj.attr 觸發 type(obj).__getattribute__('attr'),搜索順序:

  1. 類字典中的數據描述符
  2. 實例 __dict__
  3. 類字典中的非數據描述符 / 類屬性
  4. __getattr__(若定義)

數據描述符優先級最高,可覆蓋實例同名屬性——這是 property、classmethod 等內建工作的基礎。

場景二:只讀屬性(運行時初始化後凍結)

僅實現 __get__,不提供 __set__:

class ReadOnly:
    def __init__(self, value):
        self._value = value
    def __get__(self, instance, owner):
        return self._value

class Config:
    api_key = ReadOnly("SECRET-123")

c = Config()
print(c.api_key)  # SECRET-123
c.api_key = "hack"  # AttributeError: __set__ not defined

場景三:訪問日誌/審計

在 __get__/__set__ 注入日誌、驗證、緩存等橫切邏輯,實現 AOP 風格復用。

property() 內建簡化

Python 提供 property(fget, fset, fdel, doc) 工廠函數,自動生成數據描述符:

class Account:
    def __init__(self):
        self._acct_num = None

    def get_acct(self): return self._acct_num
    def set_acct(self, v): self._acct_num = v
    def del_acct(self): del self._acct_num

    acct_num = property(get_acct, set_acct, del_acct, "Account number")

等價於手寫描述符類,但更簡潔。現代 Python 更推薦 @property 裝飾器語法糖。

copyright © 萬盛學電腦網 all rights reserved