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
types.MethodType for Dynamic BindingCopy
β
Fix: MethodType ensures the function behaves as a method, keeping self bound correctly.
πΉ 4. Adding a staticmethod Dynamically
staticmethod DynamicallyCopy
β
Fix: Use staticmethod() or decorator to add static methods dynamically.
πΉ 5. Adding a classmethod Dynamically
classmethod DynamicallyCopy
β
Fix: Use classmethod() to dynamically attach a method that operates on the class itself.
πΉ 6. Adding a Method Inside __init__
__init__Copy
β
Fix: Assign a lambda function inside __init__ to define a method dynamically.
πΉ 7. Using __dict__ to Modify Methods
__dict__ to Modify MethodsCopy
β
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