Python中猴子补丁是什么?
python属性在运行时的动态替换,叫做猴子补丁(MonkeyPatch)。
为什么叫猴子补丁
python属性的运行时替换和猴子也没什么关系,关于猴子补丁的由来网上查到两种说法:
1.这个词原来为GuerrillaPatch,杂牌军、游击队,说明这部分不是原装的,在英文里guerilla发音和gorllia(猩猩)相似,再后来就写了monkey(猴子)。
2.还有一种解释是说由于这种方式将原来的代码弄乱了(messingwithit),在英文里叫monkeyingabout(顽皮的),所以叫做MonkeyPatch。
猴子补丁的叫法有些莫名其妙,只要和“模块运行时替换的功能”对应就行了。
猴子补丁的用法
1、运行时动态替换模块的方法
stackoverflow上有两个比较热的例子,
consideraclassthathasamethodget_data.Thismethoddoesan
externallookup(onadatabaseorwebAPI,forexample),andvarious
othermethodsintheclasscallit.However,inaunittest,youdon't
wanttodependontheexternaldatasource-soyoudynamically
replacetheget_datamethodwithastubthatreturnssomefixeddata.
假设一个类有一个方法get_data。这个方法做一些外部查询(如查询数据库或者WebAPI等),类里面的很多其他方法都调用了它。然而,在一个单元测试中,你不想依赖外部数据源。所以你用哑方法态替换了这个get_data方法,哑方法只返回一些测试数据。
另一个例子引用了,Zopewiki上对MonkeyPatch解释:
fromSomeOtherProduct.SomeModuleimportSomeClass
defspeak(self):
return"ookookeeeeeeeee!"
SomeClass.speak=speak
还有一个比较实用的例子,很多代码用到importjson,后来发现ujson性能更高,如果觉得把每个文件的importjson改成importujsonasjson成本较高,或者说想测试一下用ujson替换json是否符合预期,只需要在入口加上:
importjson
importujson
defmonkey_patch_json():
json.__name__='ujson'
json.dumps=ujson.dumps
json.loads=ujson.loads
monkey_patch_json()
2、运行时动态增加模块的方法
这种场景也比较多,比如我们引用团队通用库里的一个模块,又想丰富模块的功能,除了继承之外也可以考虑用MonkeyPatch。
个人感觉MonkeyPatch带了便利的同时也有搞乱源代码优雅的风险。
以上内容为大家介绍了Python中猴子补丁是什么?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
为什么Python爬虫使用MongoDB?
想必大家都知道,在从事网络爬虫工作之前,我们需要掌握很多知识,除了基本的爬虫原理之外,我们还需要学习框架、数据库等,其中就包含MongoDB...详情>>
2023-11-07 23:02:10
python如何进行类型转换的
python提供了将变量或值从一种类型转换成另一种类型的内置函数。1、int:将符合数学格式数字型字符串转换成整数。>>>int('123')1232、s...详情>>
2023-11-07 18:51:20
python怎么生成随机数
以下实例演示了python如何生成一个随机数:#生成0~9之间的随机数#导入random(随机数)模块importrandomprint(random.randint(0,9))执行以上代码...详情>>
2023-11-07 17:09:17
python如何删除空格
python中的字符串方法提供了如下常用的方法来删除空白:strip():删除字符串前后的空白。lstrip():删除字符串前面(左边)的空白。rstrip():删...详情>>
2023-11-07 14:57:44热门推荐
技术干货






