(Everything I say is false...)
home | about | articles | presentations | cv | contact


Monday 27 August 2012 (01:00AM)

Python is an easy-to-learn modern programming language with a simple yet elegant implementation of object orientation. This post explains one dark corner of Python's implementation of object orientation: metaclasses (but does so as if explaining the rules of cricket).

Objects represent things. Type, type(my_object) to find out what type of thing your object is. The type of thing an object represents is defined by its "type". Classes define types of things to be instantiated as objects. To be absolutely clear, objects represent types of things defined by classes.

Now, listen carefully!

In Python, classes are also objects. This raises an important question: what type of thing is a class?

The answer is that a class is a type of thing that can instantiate objects. This type of thing (a class's class) is a class's metaclass which, incidently, in Python defaults to a special class called type ~ whose type is, circularly, type (i.e. itself).

You can change the metaclass of a class by setting it's __metaclass__ attribute to a class that inherits from the type class. With this sleight-of-hand you can control how classes instantiate objects.

How? I'm so pleased you asked!

Override the new metaclass's __new__ method. Remember, this __new__ method must return the return of a call to the type class's __new__ method so your new class correctly instantiates a new object of the correct type.

Got it? Good!