Skip to Content
Learning Python, 6th Edition
book

Learning Python, 6th Edition

by Mark Lutz
February 2025
Intermediate to advanced
1172 pages
42h 20m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Python, 6th Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Python, 3rd Edition

Head First Python, 3rd Edition

Paul Barry

Publisher Resources

ISBN: 9781098171292Errata PageSupplemental Content