Python中的猴子补丁是什么-Python教程

资源魔 45 0

属性正在运转时的静态交换,叫做山公补钉(Monkey Patch)。

为何叫山公补钉

属性的运转时交换以及山公也没甚么关系,对于山公补钉的由来网上查到两种说法:

1.这个词原来为Guerrilla Patch,杂牌军、游击队,阐明这局部没有是原装的,正在英文里guerilla发音以及gorllia(猩猩)类似,再起初就写了monkey(山公)。

2.另有一种诠释是说因为这类形式将原来的代码弄乱了(messing with it),正在英文里叫monkeying about(玩皮的),以是叫做Monkey Patch。

山公补钉的叫法有些莫明其妙,只需以及“模块运转时交换的性能”对应就好了。

山公补钉的用法

一、运转时静态交换模块的办法

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()

二、运转时静态添加模块的办法

这类场景也比拟多,比方咱们援用团队通用库里的一个模块,又想丰厚模块的性能,除了了承继以外也能够思考用Monkey Patch。

集体觉得Monkey Patch带了便当的同时也有搅散源代码优雅的危险。

PHP中文网,有年夜量收费的Python视频教程,欢送各人学习!

本文转自:https://www.jianshu.com/p/a19f936471e4

以上就是Python中的山公补钉是甚么的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题 猴子补丁

抱歉,评论功能暂时关闭!