温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Monkey Patch怎么在Python中使用

发布时间:2021-03-31 17:00:29 来源:亿速云 阅读:135 作者:Leah 栏目:开发技术

这篇文章给大家介绍Monkey Patch怎么在Python中使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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怎么在Python中使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI