當一個class 中定義了__get__, __set__, __delete__三個函式中的任意一個,那麼這個class就可以被成為描述符。當在python中使用點 . 來呼叫某個屬性的時候,其load attr的順序如下圖所示。
關於描述符中instance 和owner的解釋
class Name: def __get__(self, instance, owner): return "peter" def __set__(self, instance, value): print("this is set function") class f: name = Name() def __init__(self): pass # self.name = "alice" fobject = f() print(fobject.name) fobject.name = "tom" print(fobject.name)