Python学习笔记-常用模块介绍--猴子补丁

1.什么是猴子补丁?

  • 属性在运行时的动态替换,叫做猴子补丁(Monkey Patch)【发音 ˈmʌŋki pætʃ】

  • 是一种思想,应用于团队引用了公共模块,想丰富模块,就在入口打这种“猴子补丁”

2.示例1:

import json
import ujson # pip3 install ujson

def monkey_patch_json():
    json.dump = ujson.dump
    json.dumps = ujson.dumps
    json.load = ujson.load
    json.loads = ujson.loads    

3.示例2:

class Monkey:
    def hello(self):
        print('hello')

    def world(self):
        print('world')

def other_func():
    print("from other_func")

monkey = Monkey()
monkey.hello = monkey.world
monkey.hello()  # 由原来的打印 hello==>world
monkey.world = other_func
monkey.world()  # 由原来的打印 world==>from other_func

 4.应用场景:

  • 如果我们的程序中已经基于json模块编写了大量代码了,发现有一个模块ujson比它性能更高,
    但用法一样,我们肯定不会想所有的代码都换成ujson.dumps或者ujson.loads,那我们可能会想到这么做
    import ujson as 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.
    采用猴子补丁之后,如果发现ujson不符合预期,那也可以快速撤掉补丁。
    个人感觉Monkey Patch带了便利的同时也有搞乱源代码的风险!
    -- 摘自《林海峰博客》

     

 

参考资料

https://www.cnblogs.com/linhaifeng/articles/6384466.html#_label6

posted @ 2023-01-11 18:41  o蹲蹲o  阅读(71)  评论(0编辑  收藏  举报