首页 > 其他 > 详细

什么是猴子补丁?

时间:2019-12-04 13:09:49      阅读:63      评论:0      收藏:0      [点我收藏+]

什么是猴子补丁?

答: 猴子补丁(monkey patching):在运行时动态修改模块、类或函数,通常是添加功能或修正缺陷。猴子补丁在代码运行时内存中)发挥作用,不会修改源码,因此只对当前运行的程序实例有效。因为猴子补丁破坏了封装,而且容易导致程序与补丁代码的实现细节紧密耦合,所以被视为临时的变通方案,不是集成代码的推荐方式。大概是下面这样的一个效果

#py3下可以运行,py2下报错

def post():
    print("this is post")
    print("想不到吧")

class Http():
    @classmethod
    def get(cls):
        print("this is get")

    @staticmethod
    def get2():
        print("this is get")

def main():
    Http.get=post #动态的修改了 get 原因的功能,

if __name__ == __main__:
    main()      
    Http.get()

python 2下报如下错误

Traceback (most recent call last):
File "E:/program/ljt_test/python_example/test/tmp.py", line 16, in <module>
Http.get()
TypeError: unbound method post() must be called with Http instance as first argument (got nothing instead)

py2修改为如下代码

#coding=utf-8

class Http:
    @classmethod
    def get(cls):
        print("this is get")

class https(Http):
    @classmethod
    def post(cls):
        print("this is post")
        print("想不到吧")

def main():
    Http.get=https.post #动态的修改了 get 原因的功能,

if __name__ == __main__:
    main()
    Http.get()

test

什么是猴子补丁?

原文:https://www.cnblogs.com/leijiangtao/p/11981324.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!