Monkey Patching: A Dynamic Modification Technique
In programming, monkey patching refers to the practice of dynamically modifying the attributes of a class or module at runtime. Unlike method or operator overloading, which involve defining multiple implementations of the same method or operator with varying parameters, monkey patching allows you to directly replace or modify existing attributes.
To understand monkey patching, consider the following scenario:
A class contains a method called get_data() that retrieves data from an external source, such as a database or web API. In a unit test, however, we may want to bypass the external data source and use a stub method that returns fixed data.
With monkey patching, we can dynamically replace the original get_data() method with our stub method:
# Original get_data() method def get_data(): # Perform external lookup # Stub get_data() method for unit testing def get_data_stub(): return 'Fixed data' # Monkey patch the get_data() method with the stub MyClass.get_data = get_data_stub
Now, when the get_data() method is called within the test case, it will execute the stub method instead of the original data retrieval logic.
Caution:
While monkey patching is a powerful technique, it should be used with care:
The above is the detailed content of What is Monkey Patching and How Does it Dynamically Modify Code?. For more information, please follow other related articles on the PHP Chinese website!