Classes

Metaclasses

A metaclass customizes how classes themselves are created.

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

Tagged
instanceCLASSClassMETACLASStype
A metaclass is the type of a class, just as a class is the type of its instances; type is the default metaclass.

The 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
Tagged

Notes

See also

Run the complete example

Example code

Expected output

event
Tagged

Execution time appears here after you run the example.