Python 简明教程
Python - Monkey Patching
Python 中的 Monkey patching 指的是在运行时动态修改或扩展代码的做法,通常通过替换或向现有 modules 、 classes or methods 中添加新功能,而无需更改其原始源代码。此技术通常用于快速修复、调试或添加临时功能。
Monkey patching in Python refers to the practice of dynamically modifying or extending code at runtime typically replacing or adding new functionalities to existing modules, classes or methods without altering their original source code. This technique is often used for quick fixes, debugging or adding temporary features.
术语“ monkey patching ”源自于临时性变化想法,类似于猴子如何使用手头的任何材料修补东西。
The term "monkey patching" originates from the idea of making changes in a way that is ad-hoc or temporary, akin to how a monkey might patch something up using whatever materials are at hand.
Steps to Perform Monkey Patching
以下是展示我们如何执行猴子修补的步骤 −
Following are the steps that shows how we can perform monkey patching −
-
First to apply a monkey patch we have to import the module or class we want to modify.
-
In the second step we have to define a new function or method with the desired behavior.
-
Replace the original function or method with the new implementation by assigning it to the attribute of the class or module.
Example of Monkey Patching
现在,让我们通过一个示例了解 Monkey patching −
Now let’s understand the Monkey patching with the help of an example −
Define a Class or Module to Patch
首先,我们必须定义我们要修改的原始类或模块。以下是代码 −
First we have to define the original class or module that we want to modify. Below is the code −
# original_module.py
class MyClass:
def say_hello(self):
return "Hello, Welcome to Tutorialspoint!"
Create a Patching Function or Method
接下来,我们必须定义一个函数或方法来对原始类或模块进行猴子修补。此函数将包含我们想要添加的新行为或功能 −
Next we have to define a function or method that we will use to monkey patch the original class or module. This function will contain the new behavior or functionality we want to add −
# patch_module.py
from original_module import MyClass
# Define a new function to be patched
def new_say_hello(self):
return "Greetings!"
# Monkey patching MyClass with new_say_hello method
MyClass.say_hello = new_say_hello
Test the Monkey Patch
现在我们可以测试已修补的功能。在用修补程序为 MyClass 创建实例之前,请确保完成了修补工作 −
Now we can test the patched functionality. Ensure that the patching is done before we create an instance of MyClass with the patched method −
# test_patch.py
from original_module import MyClass
import patch_module
# Create an instance of MyClass
obj = MyClass()
# Test the patched method
print(obj.say_hello()) # Output: Greetings!
Drawbacks of Monkey Patching
以下是猴子修补的缺点 −
Following are the draw backs of monkey patching −
-
Overuse: Excessive monkey patching can lead to code that is hard to understand and maintain. We have to use it judiciously and consider alternative design patterns if possible.
-
Compatibility: Monkey patching may introduce unexpected behavior especially in complex systems or with large code-bases.