InterviewSolution
| 1. |
What is ‘monkey patching’? How is it performed in Python? |
|
Answer» The term MONKEY patching is used to describe a technique used to dynamically MODIFY the behavior of a piece of code at run-time. This technique allows us to modify or extend the behavior of libraries, modules, classes or methods at runtime WITHOUT actually modifying the source code. Monkey patching technique is useful in the following scenarios:
In PYTHON, classes are just like any other mutable objects. Hence we can modify them or their attributes including functions or methods at runtime. In the following demonstration of monkey patching, let us first write a simple class with a method that adds two operands. #monkeytest.py class MonkeyTest: def add(self, x,y): return x+yWe can call add() method straightaway from monkeytest import MonkeyTest a=MonkeyTest() print (a.add(1,2))However, we now need to modify add() method in the above class to accept a variable number of ARGUMENTS. What do we do? First define a newadd() function that can accept variable arguments and perform addition. def newadd(s,*args): s=0 for a in args:s=s+int(a) return sNow assign this function to the add() method of our MonkeyTest class. The modified behaviour of add() method is now available for all instances of your class. MonkeyTest.add=newadd a=MonkeyTest() print (a.add(1,2,3)) |
|