Classes
Metaclasses
A metaclass customizes class creation. __new__ receives the class name, bases, and namespace before the class object exists.
Source
class Tagged(type):
def __new__(mcls, name, bases, namespace):
namespace["tag"] = name.lower()
return super().__new__(mcls, name, bases, namespace)
print(Tagged.__name__)Output
TaggedThe metaclass= keyword applies that class-building rule. Here the metaclass adds a tag attribute to the new class.
Source
class Event(metaclass=Tagged):
pass
print(Event.tag)
print(type(Event).__name__)Output
event
TaggedNotes
- Metaclasses customize class creation, not instance behavior directly.
- Most code should prefer class decorators, functions, or ordinary inheritance.
- You are most likely to meet metaclasses inside frameworks and ORMs.
See also
- related: Classes
- related: Inheritance and Super
- prerequisite: Special Methods
Run the complete example
Expected output
event
Tagged
Execution time appears here after you run the example.