A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass.
While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the more useful approach is actually to make it an actual class itself. 'type
' is the usual metaclass in Python. In case you're wondering, yes, 'type
' is itself a class, and it is its own type. You won't be able to recreate something like 'type
' purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass 'type
'.
A metaclass is most commonly used as a class-factory. Like you create an instance of the class by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal __init__
and __new__
methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry, or even replace the class with something else entirely.
When the 'class
' statement is executed, Python first executes the body of the 'class
' statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the __metaclass__
attribute of the class-to-be (if any) or the '__metaclass__
' global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.