17. Monkey Patching
1. Basic Monkey Patching of a Function
# Original function
def greet(name):
return f"Hello, {name}"
# Monkey patching the function
def new_greet(name):
return f"Hi, {name}"
greet = new_greet # Replace the original function with the new one
# Test the patched function
print(greet("John")) # Output: Hi, John2. Monkey Patching a Method of a Class
class Dog:
def speak(self):
return "Woof"
# Monkey patch the speak method
def new_speak(self):
return "Bark"
Dog.speak = new_speak # Replace the speak method
# Test the patched method
dog = Dog()
print(dog.speak()) # Output: Bark3. Monkey Patching a Module Function
4. Monkey Patching for Logging
5. Monkey Patching for Debugging
6. Monkey Patching to Extend Behavior
7. Monkey Patching to Handle Errors
8. Monkey Patching with a Wrapper
9. Monkey Patching a Class Constructor
10. Monkey Patching for Performance
Notes:
Last updated