Metaclasses
As we noted earlier, 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 attributes assignment statements will build the final, usable class we need for our application.
Here's how it works:
Figure 6.3: How type creates MyClass
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 creation of the class; 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:
Figure 6.4: Extending the type class
If we use the metaclass...