In Python, everything is an object: integers, strings, lists, even functions and classes themselves are objects. And every object is an instance of a class.
To check the class of an object x, one can call type(x)
, so:
>>> type(5)
<type 'int'>
>>> type(str)
<type 'type'>
>>> type([1, 2, 3])
<type 'list'>
>>> class C(object):
... pass
...
>>> type(C)
<type 'type'>
Most classes in python are instances of type
. type
itself is also a class. Such classes whose instances are also classes are called metaclasses.
OK, so there is already one metaclass in Python: type
. Can we create another one?
class SimplestMetaclass(type):
pass
class MyClass(object):
__metaclass__ = SimplestMetaclass
That does not add any functionality, but it is a new metaclass, see that MyClass is now an instance of SimplestMetaclass:
>>> type(MyClass)
<class '__main__.SimplestMetaclass'>
A metaclass which does something usually overrides type
's __new__
, to modify some properties of the class to be created, before calling the original __new__
which creates the class:
class AnotherMetaclass(type):
def __new__(cls, name, parents, dct):
# cls is this class
# name is the name of the class to be created
# parents is the list of the class's parent classes
# dct is the list of class's attributes (methods, static variables)
# here all of the attributes can be modified before creating the class, e.g.
dct['x'] = 8 # now the class will have a static variable x = 8
# return value is the new class. super will take care of that
return super(AnotherMetaclass, cls).__new__(cls, name, parents, dct)