python中猴子补丁是什么?怎么用?


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于python中猴子补丁是什么?怎么用?有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

什么是猴子补丁

the term monkey patch only refers to dynamic modifications of a class or module at runtime, motivated by the intent to patch existing third-party code as a workaround to a bug or feature which does not act as desired

即在运行时对方法 / 类 / 属性 / 功能进行修改,把新的代码作为解决方案代替原有的程序,也就是为其打上补丁。

为什么叫做猴子补丁

The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime.The word guerrilla, homophonous with gorilla (or nearly so), became monkey, possibly to make the patch sound less intimidating.[1] An alternative etymology is that it refers to “monkeying about” with the code (messing with it).

一种说法杂牌军、游击队的英文发音与猩猩相似,杂牌军、游击队不是原装军队,就像是替补,所以也就演变叫做猴子补丁另一种说法“monkeying about”有胡闹,顽皮,哄骗的意思,所以叫做猴子补丁

python中使用猴子补丁

1

2

3

4

5

6

7

8

9

10

class Example():

    def func1(self):

        print('我才是原装')def func2(*args):

    print('我要取代你')def func3(*args):

    print('都给我一边去')

instance = Example()

Example.func1 = func2

instance.func1() # 我要取代你instance.func1 = func3

instance.func1() # 都给我一边去instance2 = Example()

instance2.func1() # 我要取代你

例子非常简单,func2取代的是类的方法,func3取代的是实例的方法,最终输出都不是原装

其他例子

在使用gevent模块的使用就会遇到猴子补丁

1

2

import gevent.monkey

 gevent.monkey.patch_all()

使用猴子补丁的方式,gevent能够修改标准库里面大部分的阻塞式系统调用,包括socket、ssl、threading和 select等模块,而变为协作式运行。也就是通过猴子补丁的monkey.patch_xxx()来将python标准库中模块或函数改成gevent中的响应的具有协程的协作式对象。这样在不改变原有代码的情况下,将应用的阻塞式方法,变成协程式的。
这里参考https://blog.csdn.net/wangjianno2/article/details/51708658

注意问题

在使用猴子补丁的时候同样容易出现问题

当进行版本更新变化的时候,很容易对补丁做出破坏不知情的情况下对一个位置打两个补丁会造成替换对于不知道有补丁的人来说可能会对出现的某些情况感到困惑

以上就是python中猴子补丁是什么?怎么用?的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python有for循环吗

Python 怎么获取网页内容

如何加速Python程序

Python求两个数的最大公约数

怎么看Python是否安装成功?

Python是什么语言编写出来的

Python和vba学哪个

Python如何输入十个学生的成绩

怎么用Python

Python2和Python3学哪个

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...