Monkey Patching in Python
1 min readAug 31, 2018
Let’s get into the Python’s Monkey Patch. Monkey Patching is nothing but replacing a class method with another method outside the class at run time.In a word, it changes a class at run time. Let’s do it:
class MonkeyPatch:
def monkey_1(self):
return “I am monkey_1 from MonkeyPatch”
Let’s check it out in IDLE:
print MonkeyPatch().monkey_1()
The resulted output is: I am monkey_1 from MonkeyPatch
Let’s define the other method which is going to replace the class method:
def monkey_2(self):
return “I am monkey_2”
We have declared monkey_2 method. Now we can get the same return value from the class method. Let’s see:
MonkeyPatch.monkey_1 = monkey_2
print MonkeyPatch.monkey_1
The resulted output is: I am monkey_2