218. Dynamic Method Addition 1
πΉ 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!πΉ 2. Adding a Method to a Class
πΉ 3. Using types.MethodType for Dynamic Binding
types.MethodType for Dynamic BindingπΉ 4. Adding a staticmethod Dynamically
staticmethod DynamicallyπΉ 5. Adding a classmethod Dynamically
classmethod DynamicallyπΉ 6. Adding a Method Inside __init__
__init__πΉ 7. Using __dict__ to Modify Methods
__dict__ to Modify MethodsπΉ 8. Adding a Method Dynamically Using Decorators
πΉ 9. Injecting Methods via Metaclass
πΉ 10. Attaching Methods from a Module or Another Class
Last updated