1. 程式人生 > 程式設計 >Python猴子補丁知識點總結

Python猴子補丁知識點總結

屬性在執行時的動態替換,叫做猴子補丁(Monkey Patch)。

為什麼叫猴子補丁

屬性的執行時替換和猴子也沒什麼關係,關於猴子補丁的由來網上查到兩種說法:

1.這個詞原來為Guerrilla Patch,雜牌軍、游擊隊,說明這部分不是原裝的,在英文裡guerilla發音和gorllia(猩猩)相似,再後來就寫了monkey(猴子)。

2.還有一種解釋是說由於這種方式將原來的程式碼弄亂了(messing with it),在英文裡叫monkeying about(頑皮的),所以叫做Monkey Patch。

猴子補丁的叫法有些莫名其妙,只要和“模組執行時替換的功能”對應就行了。

猴子補丁的用法

1、執行時動態替換模組的方法

stackoverflow上有兩個比較熱的例子,

consider a class that has a method get_data. This method does an

external lookup (on a database or web API,for example),and various

other methods in the class call it. However,in a unit test,you don't

want to depend on the external data source - so you dynamically

replace the get_data method with a stub that returns some fixed data.

假設一個類有一個方法get_data。這個方法做一些外部查詢(如查詢資料庫或者Web API等),類裡面的很多其他方法都呼叫了它。然而,在一個單元測試中,你不想依賴外部資料來源。所以你用啞方法態替換了這個get_data方法,啞方法只返回一些測試資料。

另一個例子引用了,Zope wiki上對Monkey Patch解釋:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):

  return "ook ook eee eee eee!"

SomeClass.speak = speak

還有一個比較實用的例子,很多程式碼用到 import json,後來發現ujson效能更高,如果覺得把每個檔案的import json 改成 import ujson as json成本較高,或者說想測試一下用ujson替換json是否符合預期,只需要在入口加上:

import json

import ujson

def monkey_patch_json():

  json.__name__ = 'ujson'

  json.dumps = ujson.dumps

  json.loads = ujson.loads

monkey_patch_json()

2、執行時動態增加模組的方法

這種場景也比較多,比如我們引用團隊通用庫裡的一個模組,又想豐富模組的功能,除了繼承之外也可以考慮用Monkey Patch。

個人感覺Monkey Patch帶了便利的同時也有搞亂原始碼優雅的風險。

以上就是相關知識點總結,感謝大家的學習和對我們的支援。