Python描述器descriptor詳解
前面說(shuō)了descriptor,這個(gè)東西其實(shí)和Java的setter,getter有點(diǎn)像。但這個(gè)descriptor和上文中我們開(kāi)始提到的函數(shù)方法這些東西有什么關(guān)系呢?
所有的函數(shù)都可以是descriptor,因?yàn)樗衉_get__方法。
>>> def hello():
pass
>>> dir(hello)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '<span style="color: #ff0000;">__get__</span>
', '__getattribute__',
'__hash__', '__init__', '__module__', '__name__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure',
'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
>>>
注意,函數(shù)對(duì)象沒(méi)有__set__和__del__方法,所以它是個(gè)non-data descriptor.
方法其實(shí)也是函數(shù),如下:
>>> class T(object):
def hello(self):
pass
>>> T.__dict__['hello']
<function hello at 0x00CD7EB0>
>>>
或者,我們可以把方法看成特殊的函數(shù),只是它們存在于類 中,獲取函數(shù)屬性時(shí),返回的不是函數(shù)本身(比如上面的<function hello at 0x00CD7EB0>),而是返回函數(shù)的__get__方法的返回值,接著上面類T的定義:
>>> T.hello 獲取T的hello屬性,根據(jù)查找策略,從T的__dict__中找到了,找到的是<function hello at 0x00CD7EB0>,但不會(huì)直接返回<function hello at 0x00CD7EB0>,因?yàn)樗衉_get__方法,所以返回的是調(diào)用它的__get__(None, T)的結(jié)果:一個(gè)unbound方法。
<unbound method T.hello>
>>> f = T.__dict__['hello'] #直接從T的__dict__中獲取hello,不會(huì)執(zhí)行查找策略,直接返回了<function hello at 0x00CD7EB0>
>>> f
<function hello at 0x00CD7EB0>
>>> t = T()
>>> t.hello #從實(shí)例獲取屬性,返回的是調(diào)用<function hello at 0x00CD7EB0>的__get__(t, T)的結(jié)果:一個(gè)bound方法。
<bound method T.hello of <__main__.T object at 0x00CDAD10>>
>>>
為了證實(shí)我們上面的說(shuō)法,在繼續(xù)下面的代碼(f還是上面的<function hello at 0x00CD7EB0>):
>>> f.__get__(None, T)
<unbound method T.hello>
>>> f.__get__(t, T)
<bound method T.hello of <__main__.T object at 0x00CDAD10>>
好極了!
總結(jié)一下:
1.所有的函數(shù)都有__get__方法
2.當(dāng)函數(shù)位于類的__dict__中時(shí),這個(gè)函數(shù)可以認(rèn)為是個(gè)方法,通過(guò)類或?qū)嵗@取該函數(shù)時(shí),返回的不是函數(shù)本身,而是它的__get__方法返回值。
我承認(rèn)我可能誤導(dǎo)你認(rèn)為方法就是函數(shù),是特殊的函數(shù)。其實(shí)方法和函數(shù)還是有區(qū)別的,準(zhǔn)確的說(shuō):方法就是方法,函數(shù)就是函數(shù)。
>>> type(f)
<type 'function'>
>>> type(t.hello)
<type 'instancemethod'>
>>> type(T.hello)
<type 'instancemethod'>
>>>
函數(shù)是function類型的,method是instancemethod(這是普通的實(shí)例方法,后面會(huì)提到classmethod和staticmethod)。
關(guān)于unbound method和bound method,再多說(shuō)兩句。在c實(shí)現(xiàn)中,它們是同一個(gè)對(duì)象(它們都是instancemethod類型的),我們先看看它們里面到底是什么
>>> dir(t.hello)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', 'im_class', 'im_func', 'im_self']
__call__說(shuō)明它們是個(gè)可調(diào)用對(duì)象,而且我們還可以猜測(cè),這個(gè)__call__的實(shí)現(xiàn)應(yīng)該大致是:轉(zhuǎn)調(diào)另外一個(gè)函數(shù)(我們期望的哪個(gè),比如上面的hello),并以對(duì)象作為第一參數(shù)。
要 注意的是im_class,im_func,im_self。這幾個(gè)東西我們并不陌生,在t.hello里,它們分別代表T,hello(這里是存儲(chǔ)在 T.__dict__里的函數(shù)hello)和t。有了這些我們可以大致想象如何純Python實(shí)現(xiàn)一個(gè)instancemethod了:)。
其實(shí)還有幾個(gè)內(nèi)建函數(shù)都和descriptor有關(guān),下面簡(jiǎn)單說(shuō)說(shuō)。
classmethod
classmethod能將一個(gè)函數(shù)轉(zhuǎn)換成類方法,類方法的第一個(gè)隱含參數(shù)是類本身 (普通方法的第一個(gè)隱含參數(shù)是實(shí)例本身),類方法即可從類調(diào)用,也可以從實(shí)例調(diào)用(普通方法只能從實(shí)例調(diào)用)。
>>> class T(object):
def hello(cls):
print 'hello', cls
hello = classmethod(hello) #兩個(gè)作用:把hello裝換成類方法,同時(shí)隱藏作為普通方法的hello
>>> t = T()
>>> t.hello()
hello <class '__main__.T'>
>>> T.hello()
hello <class '__main__.T'>
>>>
注意:classmethod是個(gè)類,不是函數(shù)。classmethod類有__get__方法,所以,上面的t.hello和T.hello獲得實(shí)際上是classmethod的__get__方法返回值
>>> t.hello
<bound method type.hello of <class '__main__.T'>>
>>> type(t.hello)
<type 'instancemethod'>
>>> T.hello
<bound method type.hello of <class '__main__.T'>>
>>> type(T.hello)
<type 'instancemethod'>
>>>
從 上面可以看出,t.hello和T.hello是instancemethod類型的,而且是綁定在T上的。也就是說(shuō)classmethod的 __get__方法返回了一個(gè)instancemethod對(duì)象。從前面對(duì)instancemethod的分析上,我們應(yīng)該可以推斷:t.hello的 im_self是T,im_class是type(T是type的實(shí)例),im_func是函數(shù)hello
>>> t.hello.im_self
<class '__main__.T'>
>>> t.hello.im_class
<type 'type'>
>>> t.hello.im_func
<function hello at 0x011A40B0>
>>>
完全一致!所以實(shí)現(xiàn)一個(gè)純Python的classmethod也不難:)
staticmethod
staticmethod能將一個(gè)函數(shù)轉(zhuǎn)換成靜態(tài)方法,靜態(tài)方法沒(méi)有隱含的第一個(gè)參數(shù)。
class T(object):
def hello():
print 'hello'
hello = staticmethod(hello)
>>> T.hello() #沒(méi)有隱含的第一個(gè)參數(shù)
hello
>>> T.hello
<function hello at 0x011A4270>
>>>
T.hello直接返回了一個(gè)函數(shù)。猜想staticmethod類的__get__方法應(yīng)該是直接返回了對(duì)象本身。
還有一個(gè)property,和上面兩個(gè)差不多,它是個(gè)data descriptor。
相關(guān)文章
淺談Python腳本開(kāi)頭及導(dǎo)包注釋自動(dòng)添加方法
今天小編就為大家分享一篇淺談Python腳本開(kāi)頭及導(dǎo)包注釋自動(dòng)添加方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
python使用numpy讀取、保存txt數(shù)據(jù)的實(shí)例
今天小編就為大家分享一篇python使用numpy讀取、保存txt數(shù)據(jù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
Python開(kāi)發(fā)之Nginx+uWSGI+virtualenv多項(xiàng)目部署教程
這篇文章主要介紹了Python系列之-Nginx+uWSGI+virtualenv多項(xiàng)目部署教程,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
Python使用scipy模塊實(shí)現(xiàn)一維卷積運(yùn)算示例
這篇文章主要介紹了Python使用scipy模塊實(shí)現(xiàn)一維卷積運(yùn)算,結(jié)合實(shí)例形式分析了scipy模塊的功能及使用scipy模塊進(jìn)行一維卷積運(yùn)算的相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
Python數(shù)據(jù)可視化處理庫(kù)PyEcharts柱狀圖,餅圖,線性圖,詞云圖常用實(shí)例詳解
這篇文章主要介紹了Python數(shù)據(jù)可視化處理庫(kù)PyEcharts柱狀圖、餅圖、線性圖常用實(shí)例詳解,需要的朋友可以參考下2020-02-02
利用Python實(shí)現(xiàn)簡(jiǎn)單的Excel統(tǒng)計(jì)函數(shù)
這篇文章主要介紹了利用Python實(shí)現(xiàn)簡(jiǎn)單的Excel統(tǒng)計(jì)函數(shù),文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-07-07
python使用requests設(shè)置讀取超時(shí)時(shí)間
在Python中,使用requests庫(kù)進(jìn)行網(wǎng)絡(luò)請(qǐng)求時(shí),可以通過(guò)設(shè)置?timeout參數(shù)來(lái)指定讀取超時(shí)時(shí)間,本文就來(lái)介紹一下,具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11
關(guān)于python3.7安裝matplotlib始終無(wú)法成功的問(wèn)題的解決
這篇文章主要介紹了關(guān)于python3.7安裝matplotlib始終無(wú)法成功的問(wèn)題的解決,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Python通過(guò)wordcloud庫(kù)實(shí)現(xiàn)將單詞生成詞云
Python的wordcloud庫(kù)是一個(gè)用于生成詞云的Python包,它可以將一段文本中出現(xiàn)頻率高的單詞按其出現(xiàn)頻率大小以及顏色深淺排列成一個(gè)詞云圖形,從而更好地展示文本中的信息,你可以使用wordcloud庫(kù)來(lái)生成各種類型的詞云,本文就介紹了如何生成心型詞云2023-06-06
Python讀取sqlite數(shù)據(jù)庫(kù)文件的方法分析
這篇文章主要介紹了Python讀取sqlite數(shù)據(jù)庫(kù)文件的方法,結(jié)合實(shí)例形式分析了Python引入sqlite3模塊操作sqlite數(shù)據(jù)庫(kù)的讀取、SQL命令執(zhí)行等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08

