Python猴子补丁Monkey Patch用法实例解析
作者:python大师 时间:2022-02-20 06:45:01
属性在运行时的动态替换,叫做猴子补丁(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带了便利的同时也有搞乱源代码优雅的风险。
来源:https://www.cnblogs.com/daniumiqi/p/12154808.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
php导出excel格式数据问题
微信跳一跳自动运行python脚本
Python读取配置文件的实战操作
正则表达式学习笔记
Sql Server 2000内存调整
python爬虫开发之PyQuery模块详细使用方法与实例全解
asp如何统计字符串出现的次数?
Python采集王者最低战力信息实战示例
![](https://img.aspxhome.com/file/2023/9/72949_0s.png)
python基础知识之字典(Dict)
![](https://img.aspxhome.com/file/2023/8/100748_0s.png)
struts2+jsp+jquery+Jcrop实现图片裁剪并上传实例
![](https://img.aspxhome.com/file/2023/8/97968_0s.jpg)
go日志库中的logrus
ASP中使用Session变量的优缺点
如何处理json中不带双引号的key的问题
![](https://img.aspxhome.com/file/2023/1/89301_0s.png)
Django实现将views.py中的数据传递到前端html页面,并展示
![](https://img.aspxhome.com/file/2023/2/72262_0s.jpg)
丰富段落里的标签
Python实现数通设备端口使用情况监控实例
详解Python中的日志模块logging
![](https://img.aspxhome.com/file/2023/5/81545_0s.jpg)