218. Dynamic Method Addition


🔹 1. Adding a Method to an Instance

class Person:
    def __init__(self, name):
        self.name = name

def say_hello(self):
    return f"Hello, my name is {self.name}!"

p = Person("Alice")

# Bind method to instance
p.say_hello = say_hello.__get__(p)  

print(p.say_hello())  # ✅ Output: Hello, my name is Alice!

Fix: Use __get__() to bind a function to an instance.


🔹 2. Adding a Method to a Class

class Person:
    def __init__(self, name):
        self.name = name

def say_hello(self):
    return f"Hello, my name is {self.name}!"

# Attach method to class dynamically
Person.say_hello = say_hello  

p = Person("Bob")
print(p.say_hello())  # ✅ Output: Hello, my name is Bob!

Fix: Directly assign a function to a class, making it available to all instances.


🔹 3. Using types.MethodType for Dynamic Binding

Fix: MethodType ensures the function behaves as a method, keeping self bound correctly.


🔹 4. Adding a staticmethod Dynamically

Fix: Use staticmethod() or decorator to add static methods dynamically.


🔹 5. Adding a classmethod Dynamically

Fix: Use classmethod() to dynamically attach a method that operates on the class itself.


🔹 6. Adding a Method Inside __init__

Fix: Assign a lambda function inside __init__ to define a method dynamically.


🔹 7. Using __dict__ to Modify Methods

Fix: Modify the instance’s __dict__ to dynamically add behavior.


🔹 8. Adding a Method Dynamically Using Decorators

Fix: Use decorators to add methods dynamically before object creation.


🔹 9. Injecting Methods via Metaclass

Fix: Metaclasses allow defining methods for all instances dynamically.


🔹 10. Attaching Methods from a Module or Another Class

Fix: Borrow methods from other classes dynamically.


🚀 Summary: Ways to Dynamically Add Methods in Python

Last updated