zoukankan      html  css  js  c++  java
  • 什么是猴子补丁?

    什么是猴子补丁?

    答: 猴子补丁(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

  • 相关阅读:
    多层神经网络与C++实现
    反向传导算法的推导
    sizeof()和strlen()的区别与联系
    Pascal’s Triangle
    Multiply Strings
    spring boot 数据源 配置
    spring boot 静态资源。。
    spring boot 配置 beetl 视图解析器
    spring 使用junit
    spring aspectj 注解
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/11981324.html
Copyright © 2011-2022 走看看