Improve Your Python: What Is a Metaclass?

Jun 7, 2014#Python

The significance of understanding metaclasses lies not in using them, but in understanding what classes are in Python. For the purposes of this post, I will talk about classes in Python, and try to explain what a metaclass is.

Everything in Python is an object

It is well-known that everything in Python is an object, and classes are used to create objects.

In fact, classes are objects too.

>>> class Dog(object):
...     pass
...
>>> foo = Dog()
>>> type(foo)
<class '__main__.dog'>
>>> foo
<__main__.Dog object at 0x10baf0f10>

When we defined the class Dog, Python created an object named Dog, and the object Dog is an object as well as an object creator.

Since Dog is also an object, who creates it?

You know classes are used to create objects. Since classes are also objects, who creates these objects? Who is class's class?

Here comes metaclass.

>>> class Dog(object):
...     pass
...
>>> type(Dog)
<type 'type'>
>>> Dog.__class__
<type 'type'>

You may be asking: “Why the class Dog belongs to the class type?”

Actually, type is the built-in class creator in Python, we call the class who create classes metaclass, and function type is the built-in metaclass in Python.

We can also create a class using type manually.

>>> Dog = type('Doggy', (), {'name':'snowy', 'age':5})
>>> Dog # Now Dog is a class
<class '__main__.Doggy'>
>>> Dog.name
'snowy'
>>> Dog.__name__
'Doggy'
>>> foo = Dog() # We create a instance for class Dog
>>> foo.name
'snowy'

So what are metaclasses, anyway?

Metaclasses are just classes to create classes, we can write our own metaclasses, if we don't indicate any metaclass in our code, Python will use the built-in metaclass type to create classes.

Comments