Home  >  Article  >  Backend Development  >  Explain what monkey patching in Python means?

Explain what monkey patching in Python means?

PHPz
PHPzforward
2023-08-19 11:53:16885browse

解释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.

history

The term Monkey patch is derived from guerrilla patch, which almost means gorilla and can define the monkey species. Guerrilla patching refers to making changes secretly. But monkey patch sounds easier to pronounce, so it is now called "Monkey patch". In the word "Monkey-patch", monkey defines the word 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”)

Output

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

Hello world

After Code Monkey Patch

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()

Output

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

Hello world

The above is the detailed content of Explain what monkey patching in Python means?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete