Metaclasses
Learn about the metaclasses are and why we need them in object-oriented programming.
The type
class
Creating a new class involves work done by the type
class. The job of the type
class is to create an empty class object so the various definitions and attribute assignment statements will build the final, usable class we need for our application.
Here’s how it works:
The class
statement is used to locate the appropriate metaclass; if no special metaclass
is provided, then the type
class is used. The type
class will prepare a new, empty dictionary, called a namespace, and then the various statements in the class populate this container with attributes and method definitions. Finally, the new step completes the class creation; this is generally where we can make our changes.
Here’s a diagram showing how we can use a new class, SpecialMeta
, to tap into the way type builds a new class for us:
Why do we need the metaclass?
If we use the metaclass
option when creating a class, we change the metaclass that’s used. In the preceding diagram, SpecialMeta
is a subclass of the type
class, and it can do some special processing for our class definitions.
While we can do some clever things with this technique, it’s important to keep metaclasses in perspective. They change the way class objects ...