python屬性在運(yùn)行時(shí)的動(dòng)態(tài)替換,叫做猴子補(bǔ)丁(MonkeyPatch)。
為什么叫猴子補(bǔ)丁
python屬性的運(yùn)行時(shí)替換和猴子也沒什么關(guān)系,關(guān)于猴子補(bǔ)丁的由來網(wǎng)上查到兩種說法:
1.這個(gè)詞原來為GuerrillaPatch,雜牌軍、游擊隊(duì),說明這部分不是原裝的,在英文里guerilla發(fā)音和gorllia(猩猩)相似,再后來就寫了monkey(猴子)。
2.還有一種解釋是說由于這種方式將原來的代碼弄亂了(messingwithit),在英文里叫monkeyingabout(頑皮的),所以叫做MonkeyPatch。
猴子補(bǔ)丁的叫法有些莫名其妙,只要和“模塊運(yùn)行時(shí)替換的功能”對(duì)應(yīng)就行了。
猴子補(bǔ)丁的用法
1、運(yùn)行時(shí)動(dòng)態(tài)替換模塊的方法
stackoverflow上有兩個(gè)比較熱的例子,
consideraclassthathasamethodget_data.Thismethoddoesan
externallookup(onadatabaseorwebAPI,forexample),andvarious
othermethodsintheclasscallit.However,inaunittest,youdon't
wanttodependontheexternaldatasource-soyoudynamically
replacetheget_datamethodwithastubthatreturnssomefixeddata.
假設(shè)一個(gè)類有一個(gè)方法get_data。這個(gè)方法做一些外部查詢(如查詢數(shù)據(jù)庫(kù)或者WebAPI等),類里面的很多其他方法都調(diào)用了它。然而,在一個(gè)單元測(cè)試中,你不想依賴外部數(shù)據(jù)源。所以你用啞方法態(tài)替換了這個(gè)get_data方法,啞方法只返回一些測(cè)試數(shù)據(jù)。
另一個(gè)例子引用了,Zopewiki上對(duì)MonkeyPatch解釋:
fromSomeOtherProduct.SomeModuleimportSomeClass
defspeak(self):
return"ookookeeeeeeeee!"
SomeClass.speak=speak
還有一個(gè)比較實(shí)用的例子,很多代碼用到importjson,后來發(fā)現(xiàn)ujson性能更高,如果覺得把每個(gè)文件的importjson改成importujsonasjson成本較高,或者說想測(cè)試一下用ujson替換json是否符合預(yù)期,只需要在入口加上:
importjson
importujson
defmonkey_patch_json():
json.__name__='ujson'
json.dumps=ujson.dumps
json.loads=ujson.loads
monkey_patch_json()
2、運(yùn)行時(shí)動(dòng)態(tài)增加模塊的方法
這種場(chǎng)景也比較多,比如我們引用團(tuán)隊(duì)通用庫(kù)里的一個(gè)模塊,又想豐富模塊的功能,除了繼承之外也可以考慮用MonkeyPatch。
個(gè)人感覺MonkeyPatch帶了便利的同時(shí)也有搞亂源代碼優(yōu)雅的風(fēng)險(xiǎn)。
以上內(nèi)容為大家介紹了Python中猴子補(bǔ)丁是什么?希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。