Question 16: Understanding Monkey Patching in Python

Monkey patching is a technique to extend or modify the behavior of libraries or classes at runtime.

It is often used to change or extend the behavior of a method or a class without modifying the original source code.

This can be useful for testing, debugging, or dynamically adding features.

Question: Monkey Patching in Python

In the context of monkey patching in Python, consider the following code snippet:

class Calculator:
    def add(self, x, y):
        return x + y


calc = Calculator()
print(calc.add(10, 5))  # Output: 15

def new_add(self, x, y):
    return x * y

Calculator.add = new_add

# Modified behavior
print(calc.add(10, 5))  # What will this output?

What will be the output of the modified calc.add(10, 5) after applying the monkey patch?















Answer: B. 50

Explanation:

After the original add method of the Calculator class is monkey-patched with new_add, the add method now multiplies the two arguments instead of adding them. Thus, calc.add(10, 5) will return 10 * 5, which is 50.

Leave a Reply