首页  >  文章  >  后端开发  >  解释Python中的monkey patching是什么意思?

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

PHPz
PHPz转载
2023-08-19 11:53:16822浏览

解释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删除