dynamically add a method to an instance of a class

We can dynamically add a method to an instance of a class with the help of type module and creating the lambda function, you should ensure that self is passed correctly. On the other hand, it is called monkey patching- Monkey patching involves dynamically modifying or extending code at runtime, typically by changing or adding methods and attributes to classes or modules.

from types import MethodType

class MyClass:
    language = 'java'

# Create an instance of MyClass
obj = MyClass()
# Define a lambda function and bind it as a method to obj
obj.say_hello = MethodType(lambda self: f"hello India I love {self.language}", obj)

print(obj.say_hello())

Output : hello India I love java


we are dynamically adding a new method named say_hello to the obj instance of the MyClass class. This method is added to the object at runtime; it was not defined in the initial class definition. This is considered monkey patching because it modifies the object's behavior dynamically. Monkey patching can be a useful technique, but it's important to use it judiciously as it can make code harder to understand and maintain if overused. It is frequently used in situations such as enhancing or repairing functionality in third-party libraries, introducing stopgap features, or changing behavior without changing the original source code.

Comments