描述符是實現了描述符協議的對象,即定義了 __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'),搜索順序:
__dict____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 風格復用。
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 裝飾器語法糖。