w3resource

Python Dynamic Class Inheritance: Create Subclasses

Python Metaprogramming: Exercise-11 with Solution

Generating Classes with Inheritance from Templates:

Write a Python function “generate_inherited_class” that takes a class name, a base class, and a dictionary of attributes and methods, and returns a dynamically generated subclass.

Sample Solution:

Python Code :

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

# Define a base class
class Animal:
    # Method to be inherited by subclasses
    def speak(self):
        return "Animal sound"

# Define attributes and methods for the subclass
subclass_attrs = {
    # Override the speak method
    'speak': lambda self: "Bark",
    # Add a new attribute
    'legs': 4
}

# Generate the subclass dynamically
Dog = generate_inherited_class('Dog', Animal, subclass_attrs)

# Test the dynamically generated subclass
# Create an instance of Dog
dog = Dog()
# Call the speak method (overridden)
print(dog.speak())  # Output: "Bark"
# Access the legs attribute
print(dog.legs)     # Output: 4

Output:

Bark
4

Explanation:

  • Function Definition:
    • generate_inherited_class takes 'name' (the class name), 'base_class' (the class to inherit from), and 'attrs' (attributes and methods for the subclass).
    • It uses the 'type' function to create a new class that inherits from 'base_class' and includes the attributes and methods defined in 'attrs'.
  • Base Class:
    • 'Animal' is a base class with a 'speak' method that returns "Animal sound".
  • Subclass Attributes and Methods:
    • subclass_attrs is a dictionary containing:
      • An overridden 'speak' method that returns "Bark".
      • A new attribute 'legs' with a value of 4.
  • Generate Subclass:
    • 'Dog' is dynamically created as a subclass of 'Animal' with the specified attributes and methods.
  • Testing:
    • An instance of 'Dog' is created.
    • The 'speak' method is called, which returns "Bark" due to the override.
    • The 'legs' attribute is accessed, which returns 4.

Python Code Editor :

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

Previous: Python Code Generation: Transform Templates.
Next: Dynamic Function Generation in Python: Complex Functions.

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.