Python Dynamic Method Addition: Expand Class Behavior

Python Metaprogramming: Exercise-6 with Solution

Adding Methods Dynamically:

Write Python a function "add_method" that takes a class, a method name, and a method, and adds that method to the class.

Sample Solution:

Python Code :

# Function to add a method to a class dynamically
def add_method(cls, method_name, method):
    # Use setattr to add the method to the class
    setattr(cls, method_name, method)

# Define an empty class
class MyClass:

# Define a method to be added to the class
def greet(self):
    return "Hello, dynamically added method!"

# Add the 'greet' method to 'MyClass' dynamically
add_method(MyClass, 'greet', greet)

# Test the dynamic method addition
# Create an instance of MyClass
instance = MyClass()
# Call the dynamically added 'greet' method
print(instance.greet())  # Output: "Hello, dynamically added method!" 


Hello, dynamically added method!


  • Function Definition:
    • "add_method" takes 'cls' (the class to add the method to), 'method_name' (the name of the method), and 'method' (the method function itself).
  • Add Method:
    • setattr(cls, method_name, method) adds the method to the class using the given method name.
  • Class Definition:
    • "MyClass" is defined as an empty class.
  • Method Definition:
    • "greet" is a function that returns the string "Hello, dynamically added method!".
  • Add Method to Class:
    • add_method(MyClass, 'greet', greet) adds the "greet" method to "MyClass" dynamically.
  • Testing:
    • An instance of "MyClass" is created.
    • The "greet" method is called on the instance, returning "Hello, dynamically added method!".

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Python Dynamic Class Creation: Flexibility Unleashed.
Next: Python Dynamic Class Creation: Flexible Method Inclusion.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.