Home

metaclass

A metaclass is a class whose instances are classes. In object-oriented programming, a metaclass defines the behavior of classes themselves, including how they are created, what attributes they have, and how they participate in inheritance. Metaclasses provide a way to customize class construction and to impose structure or behavior on a group of classes.

In Python, every class has a metaclass, with the default being type. A class can specify a

Metaclasses are commonly used to enforce coding standards, inject common methods, register classes automatically, or implement

A key distinction is that a class is a blueprint for objects, while a metaclass is a

metaclass
by
using
a
metaclass
declaration,
and
that
metaclass
governs
the
creation
and
initialization
of
the
class
object.
A
metaclass
can
implement
methods
such
as
__new__
and
__init__
to
control
how
the
class
object
is
created
and
initialized,
and
__prepare__
to
customize
the
class
namespace
before
it
is
populated.
It
can
also
override
__call__
to
influence
how
instances
of
the
class
are
created,
effectively
tying
instance
creation
to
the
metaclass.
cross-cutting
behavior
such
as
logging,
validation,
or
access
control
at
class
creation
time.
They
can
also
be
used
by
libraries
and
frameworks,
for
example
to
define
base
behaviors
for
data
models
in
an
ORM,
to
automatically
map
class
attributes
to
fields,
or
to
collect
metadata
about
subclasses.
blueprint
for
classes.
Using
metaclasses
adds
power
and
flexibility,
but
also
complexity,
so
they
are
typically
employed
when
substantial
control
over
class
creation
or
organization
is
needed.
Some
languages
offer
similar
capabilities
under
different
names
(such
as
eigenclasses
in
Ruby),
but
the
explicit
metaclass
mechanism
is
most
closely
associated
with
Python.