Chapter 40. Metaclasses and Inheritance
In Chapter 39, we explored decorators and studied examples of their use. In this final technical chapter of the book, we’re going to continue our tool-builders focus with an in-depth review of another advanced topic: metaclasses, a protocol for managing class objects instead of their instances, introduced briefly in Chapter 32.
On a base level, metaclasses extend the code-insertion model of decorators. As we learned in the prior chapter, decorators allow us to augment functions and classes by intercepting their creation. Metaclasses similarly allow us to intercept and augment class creation—they provide a hook for inserting extra logic to be run at the conclusion of a class statement, albeit in different ways than decorators.
Metaclasses can also provide behavior for classes with methods located in a separate inheritance tree skipped for normal, nonclass instances. While this allows metaclasses to process their instance classes after creation, it also compounds class semantics and convolutes inheritance—whose full definition can finally be fleshed out here.
Like all the subjects covered in this part of the book, this is an advanced topic that can be studied on an as-needed basis. Metaclasses are not generally in scope for most application programmers but may be of interest to others seeking to write flexible tools. Whatever category you fall into, though, metaclasses can teach you more about Python’s classes and are a prerequisite to both ...