python descriptor 與 attributor search order

1. descriptor是一個對象,是一個class
2.descriptor是一個有__get__,__set__,__delete__方法的類
3.假設D是一個有上面三個方法的類,E是一個類,其中d是其的一個成員,d是D的實例,e是E的一個實例,e.d會調用D的__get__方法,get方法的參數爲(self = d,obj = c,type = C) , e.d = f會調用d的__set__方法,參數一樣,del e.d 會調用d的delete方法

4. 由於python尋找屬性時會首先尋找類的descriptor,所以如果直接修改實例的__dict__裏的desciptor,即e.__dict__['d'] = xxx,不會影響到這個descriptor

5. 有前面的描述可知,如果要去掉d這個成員,必須要通過E.d = xxx來實現,即實例本身是沒有辦法做到的,因此python增加了data descriptor與non-data descriptor,區別在於non-data descriptor只有__get__方法,沒有另外兩個方法,即只是一個數據存儲的地方,python中的function就是這樣的descriptor,當get function是,function將self變量插入到參數列表中然後返回一個新的函數對象,因此python的search order爲:
    a. python 預定義的屬性
    b. __class__ 裏的data descriptor
    c. self.__dict__
    d. __class__.__dict__
    e. raise attribute error
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章