猴子补丁(Monkey Patching)

猴子补丁是我在面试的时候接触的一到题,学python的时候,我根本就没有听说这个概念!那接下来我们来分析一下:

  1.什么是猴子补丁?

  2.猴子补丁的功能?

  3.猴子补丁的应用场景?

 

一.什么是猴子补丁?

  1,这个词原来为Guerrilla Patch,杂牌军、游击队,说明这部分不是原装的,在英文里guerilla发音和gorllia(猩猩)相似,再后来就写了monkey(猴子)。
  2,还有一种解释是说由于这种方式将原来的代码弄乱了(messing with it),在英文里叫monkeying about(顽皮的),所以叫做Monkey Patch。

  名字听起来稀奇古怪的, 跟python的这个功能搭不上边, 所以我们直接来说功能吧!

二. 猴子补丁的功能(一切皆对象)

  1.拥有在模块运行时替换的功能, 例如: 一个函数对象赋值给另外一个函数对象(把函数原本的执行的功能给替换了)

  

 1 class Monkey:
 2     def hello(self):
 3         print('hello')
 4 
 5     def world(self):
 6         print('world')
 7 
 8 
 9 def other_fun(a=1):
10     print(a)
11 
12 
13 
14 monkey = Monkey()
15 monkey.hello = monkey.world
16 monkey.hello()
17 monkey.world = other_fun
18 monkey.world()
View Code

 

三.monkey patch的应用场景

    这里有一个比较实用的例子,很多到吗用到import json, 后来发现ujson性能更高,如果觉得把每个文件的import json改成import ujson as json成本较高, 或者说想测试一下ujson替换是否符合预期, 只需要在入口加上:

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带了便利的同时也有搞乱源代码的风险!

posted @ 2019-07-12 12:33  wakyde  阅读(2974)  评论(0编辑  收藏  举报