Dynamic Classes

Learn how to create classes with the type() function.

Custom metaclasses can modify classes by performing further actions or adding code. Usually, we do not require custom metaclasses, but sometimes they are necessary.

Dynamic creation of a class

In the previous lesson, we examined the types of different objects by passing a single argument to the type() function. That’s certainly not the end; this function can do much more. We can also create the classes using the type() function. Isn’t this amazing?

We can also call type() with three arguments:

type(<name>, <base>, <dct>)
  • The <name> is the name of the class. If passed, it becomes the __name__ attribute of the class.
  • The <base> is the tuple of the base classes from which the class inherits. If passed, it becomes the __base__ attribute of the class.
  • The <dct> is the local namespace of the class containing the definitions for the class body, which includes class methods and variables. If passed, it becomes the __dict__ attribute of the class.

Creating classes with type()

Without any further ado, let’s start creating dynamic classes by using different variations of type().

Variation I

Take the example of the following class:

class A:
  pass

Now let’s create the same class dynamically.

Get hands-on with 1200+ tech skills courses.