218. Dynamic Method Addition 1

πŸ”Ή 1. Adding a Method to an Instance

Copy

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

Copy

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


πŸ”Ή 3. Using types.MethodType for Dynamic Binding

Copy

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


πŸ”Ή 4. Adding a staticmethod Dynamically

Copy

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


πŸ”Ή 5. Adding a classmethod Dynamically

Copy

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


πŸ”Ή 6. Adding a Method Inside __init__

Copy

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


πŸ”Ή 7. Using __dict__ to Modify Methods

Copy

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


πŸ”Ή 8. Adding a Method Dynamically Using Decorators

Copy

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


πŸ”Ή 9. Injecting Methods via Metaclass

Copy

βœ… Fix: Metaclasses allow defining methods for all instances dynamically.


πŸ”Ή 10. Attaching Methods from a Module or Another Class

Copy

βœ… Fix: Borrow methods from other classes dynamically.


Last updated