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]: typetype can also take three arguments name, bases and namespace
name: name of the classbases: tuple of base classes for inheritencenamespace: 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