Metaclasses

When you define a class in Python, the class definition itself becomes an object. For example:

class Foo(object): pass
isinstance(Foo,object)      # Returns True

If you think about this long enough, you will realize that something had to create the Foo object. This creation of the class object is controlled by a special kind of object called a metaclass. Simply stated, a metaclass is an object that knows how to create and manage classes.

In the preceding example, the metaclass that is controlling the creation of Foo is a class called type. In fact, if you display the type of Foo, you will find out that it is a type:

>>> print type(Foo)
<type 'type'>

When a new class is defined with the class statement, a number of things happen. First, ...

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.