解释Python中的monkey patching是什么意思?

PHPz
发布: 2023-08-19 11:53:16
转载
876 人浏览过

解释Python中的monkey patching是什么意思?

Monkey patching is the technique of dynamic modification of a piece of code at the run time. Actually by doing monkey patch we change the behavior of code but without affecting the original source code.

历史

Monkey patch(猴子补丁)一词源自游击补丁(guerrilla patch),guerrilla几乎意味着大猩猩,可以定义猴子物种。游击补丁指的是秘密地进行变更。但是猴子补丁听起来更容易发音,所以现在被称为“Monkey patch”。在“Monkey-patch”一词中,monkey定义了dynamic(动态)这个词。

Monkey patching in python

Monkey patching in python refers to modifying or updating a piece of code or class or any module at the runtime. In simple words, we can change the behavior or working of a class/ module at the runtime without changing the whole python code. But sometimes monkey patching is considered bad practice because the definition of object does not accurately describe how the object is behaving in the code.

Example

class first:
   def print(self)
      print(“hello world”)
登录后复制

输出

If we run the above code it will generate the following output −

Hello world
登录后复制
登录后复制

代码猴子补丁后

Example

Import monkey
def monkey_function(self):
   print(“Hello world”)
# updating the print() with monkey_function()
monkey.A.print = monkey_function

# revoking method print() as method monkey_function()
obj = monkey.A()
obj print()
登录后复制

输出

If we run the above code it will generate the following output −

Hello world
登录后复制
登录后复制

以上是解释Python中的monkey patching是什么意思?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板