Explain what monkey patching in Python means?

PHPz
Release: 2023-08-19 11:53:16
forward
873 people have browsed it

解释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”)
Copy after login

Output

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

Hello world
Copy after login
Copy after login

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()
Copy after login

Output

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

Hello world
Copy after login
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template