Python Dynamic Class Inheritance: Expand with Subclass

Python Metaprogramming: Exercise-8 with Solution

Dynamic Class Inheritance:

Write a Python function "create_inherited_class" that takes a base class, a class name, and a dictionary of additional attributes and methods, and returns a dynamically created subclass.

Sample Solution:

Python Code :

# Function to create a subclass dynamically
def create_inherited_class(base_class, name, attrs):
    # Create a new class that inherits from base_class with additional attributes and methods
    return type(name, (base_class,), attrs)

# Define a base class
class BaseClass:
    # Method to be inherited by subclasses
    def base_method(self):
        return "Base method"

# Define additional attributes and methods for the subclass
additional_attrs = {
    # Add a new method to the subclass
    'additional_method': lambda self: "Additional method"

# Create a subclass dynamically using the base class and additional attributes
DynamicSubclass = create_inherited_class(BaseClass, 'DynamicSubclass', additional_attrs)

# Test the dynamic subclass
# Create an instance of the dynamically created subclass
instance = DynamicSubclass()
# Call the inherited method from the base class
print(instance.base_method())       # Output: "Base method"
# Call the newly added method in the subclass
print(instance.additional_method())  # Output: "Additional method"


Base method
Additional method


  • Function Definition:
    • 'create_inherited_class' takes 'base_class' (the class to inherit from), name (the name of the new subclass), and 'attrs' (a dictionary of additional attributes and methods).
  • Create Subclass:
    • The "type" function is used to create a new class that inherits from 'base_class' and includes the attributes and methods defined in 'attrs'.
  • Base Class Definition:
    • "BaseClass" is defined with a method 'base_method' that returns "Base method".
  • Additional Attributes and Methods:
    • 'additional_attrs' is a dictionary containing an additional method 'additional_method' that returns "Additional method".
  • Create Subclass:
    • 'DynamicSubclass' is created dynamically by calling 'create_inherited_class' with 'BaseClass', the name 'DynamicSubclass', and the additional attributes.
  • Testing:
    • An instance of 'DynamicSubclass' is created.
    • The 'base_method' inherited from 'BaseClass' is called, returning "Base method".
    • The 'additional_method' added to 'DynamicSubclass' is called, returning "Additional method".

Python Code Editor :

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

Previous: Python Dynamic Class Creation: Flexible Method Inclusion.
Next: Python Code Generation: Transform Templates.

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.