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