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!🔹 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!🔹 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
🚀 Summary: Ways to Dynamically Add Methods in Python
Last updated