Dynamically creating classes
Metaclasses are the factories that create new classes in Python. In fact, even though you may not be aware of it, Python will always execute the type
metaclass whenever you create a class.
When creating classes in a procedural way, the type
metaclass is used as a function. This function takes three arguments: name
, bases
, and dict
. The name will become the __name__
attribute, the bases
is the list of inherited base classes and will be stored in __bases__
and dict
is the namespace dictionary that contains all variables and will be stored in __dict__
.
It should be noted that the type()
function has another use as well. Given the arguments documented earlier, it creates a class given those specifications. Given a single argument with the instance of a class, it will return the class as well but from the instance. Your next question might be, "What happens if I call type()
on a class definition instead of a class instance?" Well, that returns the metaclass for the...