How to create a Class dynamically with type() in Python?


Create a class dynamically

In Python, to create a class dynamically, you can use type() built-in function. This can be used to create user defined classes on the fly, without changing the code when a new class type is required.

Consider the following simple example, where we create a class named MyClass of type object, with attributes: x.

MyClass = type('MyClass', (object,), {'x': 42})

In this tutorial, we will learn how to create a class dynamically, with examples.

Examples

1. Create a class dynamically with given classname and attributes

In this example, we define a function that creates and returns a class. The function has two parameters. First argument is the classname, and the second argument is a dictionary representing the attributes of the class.

Python Program

def createClass(classname, attributes):
    return type(classname, (object,), attributes)

Car = createClass('Car', {'name':'Audi', 'age':5})

mycar = Car()
print(f"Car name: {mycar.name}\nCar age: {mycar.age} years")

Output

Car name: Audi
Car age: 5 years

2. Create a class dynamically with a constructor

In this example, we define a function that creates and returns a class with a constructor.

Python Program

def createClass(classname, attributes):
    return type(classname, (object,), {
        '__init__': lambda self, arg1, arg2: setattr(self, 'args', (arg1, arg2)),
        'args': attributes
    })

Car = createClass('Car', {'name':'', 'age':0})

mycar = Car('Audi R8', 3)
print(f"Car name: {mycar.args[0]}\nCar age: {mycar.args[1]} years")

Output

Car name: Audi R8
Car age: 3 years

3. Create a class dynamically with a constructor

In this example, we consider the function defined in the previous example, and create class types: Car and Student dynamically.

Python Program

def createClass(classname, attributes):
    return type(classname, (object,), {
        '__init__': lambda self, arg1, arg2: setattr(self, 'args', (arg1, arg2)),
        'args': attributes
    })

Car = createClass('Car', {'name':'', 'age':0})
Student = createClass('Student', {'name':'', 'age':0})

mycar = Car('Audi R8', 3)
print(f"Car name: {mycar.args[0]}\nCar age: {mycar.args[1]} years")

student1 = Student('Ram', 12)
print(f"Student name: {student1.args[0]}\nStudent age: {student1.args[1]} years")

Output

Car name: Audi R8
Car age: 3 years
Student name: Ram
Student age: 12 years

Summary

In this tutorial of Python Examples, we learned how to use type() function to create a class type dynamically.