1from SomeOtherProduct.SomeModule import SomeClass
2
3def speak(self):
4 return "ook ook eee eee eee!"
5
6SomeClass.speak = speak
1In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time.
2filter_none
3
4# monk.py
5class A:
6 def func(self):
7 print ("func() is being called")
8
9We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.
10filter_none
11
12import monk
13def monkey_f(self):
14 print ("monkey_f() is being called")
15# replacing address of "func" with "monkey_f"
16monk.A.func = monkey_f
17obj = monk.A()
18# calling function "func" whose address got replaced
19# with function "monkey_f()"
20obj.func()
21