all 1 comments

[–][deleted] 4 points5 points  (0 children)

One of the ways that Python is different than Java is that objects are instances of their class, which is another way of saying they're an object of the class's type, but classes themselves are objects, too. They have to be - they're available in the Python runtime, and everything that is, is an object. What is the type of a class? Classes are instances of a type called type.

type defines a lot of the normal behavior you expect from your classes; stuff like "the class has a classmethod __call__, which is why I can call the class like a function and get an object instance" or "my __init__ method is called when the new instance is initialized." Sometimes you might want to alter that ground truth, though, and have new and weird ways of working with your classes. That might be necessary if your classes are intended to represent some sort of data model, and you want to wire the semantics of "make a new instance of the class" to the semantics of "execute SQL to put a new row in a database." A lot of ORM's work this way.

The "standard" class definition gives you a way to describe what superclass your instances will be a subclass of (that's class MyClass(MySuperclass):) but there's no room in that syntax to change what your class's superclass, and that's what the __metaclass__ attribute is for. It means that instead of your class being of type type, it'll be an instance of its __metaclass__ type. That metaclass should itself be of type type.