Python描述符descriptor使用原理解析
描述符(descriptor)是實(shí)現(xiàn)了__get__、__set__、__del__方法的類(lèi),進(jìn)一步可以細(xì)分為兩類(lèi):
數(shù)據(jù)描述符:實(shí)現(xiàn)了__get__和__set__
非數(shù)據(jù)描述符:沒(méi)有實(shí)現(xiàn)__set__
描述符在類(lèi)的屬性調(diào)用中起著很重要的作用,類(lèi)在調(diào)用屬性時(shí),遵守兩個(gè)規(guī)則:
按照實(shí)例屬性、類(lèi)屬性的順序選擇屬性,即實(shí)例屬性?xún)?yōu)先于類(lèi)屬性
如果在類(lèi)屬性中發(fā)現(xiàn)同名的數(shù)據(jù)描述符,那么該描述符會(huì)優(yōu)先于實(shí)例屬性
非數(shù)據(jù)描述符會(huì)被實(shí)例屬性覆蓋
class A: def __get__(self, obj, cls): return f'{obj}: get'class B: value = A() def __init__(self): self.value = 4def main(): g = B() print(g.value) print(g.__dict__)if __name__ == '__main__': main()
輸出結(jié)果
4{’value’: 4}
數(shù)據(jù)描述符優(yōu)于實(shí)例屬性
class A: def __get__(self, obj, cls): return f'{obj}: get' def __set__(self, obj, value): print(f'{obj}: set, {value}')class B: value = A() def __init__(self): self.value = 4def main(): g = B() print(g.value) print(g.__dict__)if __name__ == '__main__': main()
輸出結(jié)果
<__main__.B object at 0x000001165EB85898>: set, 4<__main__.B object at 0x000001165EB85898>: get{}
從上述兩個(gè)例子中可以看到,類(lèi)B的value屬性是一個(gè)描述符,當(dāng)value屬性是一個(gè)數(shù)據(jù)描述符時(shí),它屏蔽了實(shí)例的同名屬性value,實(shí)例對(duì)value屬性的讀取與賦值都會(huì)直接被轉(zhuǎn)移到類(lèi)屬性value上。
使用描述符實(shí)現(xiàn)類(lèi)的靜態(tài)方法與類(lèi)方法
from functools import partialclass Staticmethod: def __init__(self, method): self.method = method def __get__(self, obj, cls): return self.methodclass Classmethod: def __init__(self, method): self.method = method def __get__(self, obj, cls): return partial(self.method, cls)class A: @Staticmethod def f(self): print(f'I’m method f, the value is {self}') @Classmethod def c(self): print(f'my class is {self}')a = A()a.f(23)A.f(23)a.c()A.c()
輸出結(jié)果
I’m method f, the value is 23I’m method f, the value is 23my class is <class ’__main__.A’>my class is <class ’__main__.A’>
靜態(tài)方法與類(lèi)方法統(tǒng)一了類(lèi)屬性的兩種引用方式。這種統(tǒng)一的過(guò)程可以使用描述符修改屬性訪(fǎng)問(wèn)的默認(rèn)方式實(shí)現(xiàn)。靜態(tài)方法限制實(shí)例的默認(rèn)綁定,將方法當(dāng)做普通函數(shù)使用;類(lèi)方法始終將類(lèi)作為第一個(gè)參數(shù)傳入,上述的partial將類(lèi)固定為方法的第一個(gè)參數(shù)。
總結(jié)
描述符是實(shí)現(xiàn)了__get__、__set__、__del__等特殊方法的類(lèi),在屬性訪(fǎng)問(wèn)時(shí)起著很大的作用。 數(shù)據(jù)描述符會(huì)覆蓋同名的實(shí)例屬性,通過(guò)使用數(shù)據(jù)描述符,達(dá)到通過(guò)實(shí)例修改類(lèi)變量的目的。 描述符用于修改屬性的默認(rèn)訪(fǎng)問(wèn)方式,借此可以實(shí)現(xiàn)類(lèi)方法與靜態(tài)方法。以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 小技巧處理div內(nèi)容溢出2. HTML DOM setInterval和clearInterval方法案例詳解3. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單4. chat.asp聊天程序的編寫(xiě)方法5. python使用ProjectQ生成量子算法指令集6. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能7. python實(shí)現(xiàn)貪吃蛇游戲源碼8. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)9. xml中的空格之完全解說(shuō)10. PHP字符串前后字符或空格刪除方法介紹
