Create class dynamically

Classes are created using type() where type is built-in class or metaclass. All the classes derive this type that we can see as follows.

In [100]: class A:
     ...:     value = 100
     ...:
 
In [101]:
 
In [101]: type(A)
Out[101]: type

type can also take three arguments name, bases and namespace

  1. name: name of the class
  2. bases: tuple of base classes for inheritence
  3. namespace: body of the class, which becomes __dict__.

Following snippet shows the creation of simple class A.

def initialise_class(self, value):
     self.value = value
 
A = type("A", (), {
    "value": 100,
    "get": lambda self: self.value,
    "__init__": initialise_class
    })
 
a = A()

where value becomes the class attribute. get and __init__ are class methods. However, __init__ will be called to initialise this class.

Above class creation is same as follows,

Class A:
    value = 100
    def __init__(self, value):
        self.value = value
    def get(self):
        return self.value

References

  1. https://realpython.com/python-metaclasses/#defining-a-class-dynamically