卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

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

解释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中,datetime.date类的fromtimestamp()函数的翻译如下:
下一篇: 在GitHub上有哪些好的Python项目?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏