Python 3 Metaclass in 3 Minutes
Python metaclass is a mechanism for customizing class creation.
The default class creation is by calling:
You may a customize a class creation by:
…or by inheriting from a metaclass-created class.
Basically this is how a class is created:
-
An appropriate metaclass is determined. (If it is not unique, a
TypeError
is thrown.) -
If you implement
__prepare__
, a dict-like object (usually callednamespace
) is created by:metaclass.__prepare__(name, bases, **kwds)
Note:
__prepare__
is usually a class method (less often a static method). -
The class body is executed approximately as:
exec(body, globals(), namespace)
-
The class object is created by calling:
metaclass(name, bases, namespace, **kwds)
- The metaclass is usually inherited from
type
, and you usually implement__new__
(less often__init__
). - (As a matter of fact,
metaclass
can be any callable object.)
- The metaclass is usually inherited from
-
The class object is passed to any class decorators.
By the way, __new__()
is a static method
(special-cased so that you need not to declare it as such).