w3resource

Python Dynamic Class Creation: Flexibility Unleashed


Creating Classes Dynamically:

Write a Python function “create_class” that takes a class name and a dictionary of attributes and methods, and returns a dynamically created class with those attributes and methods.

Sample Solution:

Python Code :

# Function to create a class dynamically with specified attributes and methods
def create_class(name, attrs):
    # Use the type function to create a new class with the given name, inheriting from object, and using the specified attributes and methods
    return type(name, (object,), attrs)

# Define attributes and methods for the dynamic class
attrs = {
    # Add a method 'greet' that returns a greeting string
    'greet': lambda self: "Hello, Sonia Toutatis!",
    # Add an attribute 'age' with value 25
    'age': 25
}

# Create a class dynamically using the defined attributes and methods
MyDynamicClass = create_class('MyDynamicClass', attrs)

# Test the dynamic class
# Create an instance of the dynamically created class
instance = MyDynamicClass()
# Call the 'greet' method of the instance
print(instance.greet())  # Output: "Hello, Sonia Toutatis!"
# Access the 'age' attribute of the instance
print(instance.age)  # Output: 25 

Output:

Hello, Sonia Toutatis!
25

Explanation:

  • Function Definition:
    • "create_class" takes 'name' (the name of the class) and 'attrs' (a dictionary of attributes and methods).
  • Create Class:
    • The "type" function is used to create a new class with the given 'name', inheriting from 'object', and using the specified 'attrs'.
  • Attributes and Methods Definition:
    • attrs is a dictionary containing:
      • greet: A method that returns the string "Hello, Sonia Toutatis!".
      • age: An attribute with the value 25.
  • Create Dynamic Class:
    • "MyDynamicClass" is created dynamically by calling 'create_class' with the class name and attributes.
  • Testing:
    • An instance of 'MyDynamicClass' is created.
    • The "greet" method of the instance is called, returning "Hello, Sonia Toutatis!".
    • The 'age' attribute of the instance is accessed, returning 25.

Python Code Editor :

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

Previous: Python Attribute Logging Metaclass: Monitor Accesses.
Next: Python Dynamic Method Addition: Expand Class Behavior.

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.