Chapter 15. Metaclasses
A metaclass is to a class what a class is to an instance; that is, a metaclass is used to create classes, just as classes are used to create instances. And just as we can ask whether an instance belongs to a class by using isinstance()
, we can ask whether a class object (such as dict
, int
, or SortedList
) inherits another class using issubclass()
.
The simplest use of metaclasses is to make custom classes fit into Python’s standard ABC hierarchy. For example, to make SortedList
a collections. Sequence
, instead of inheriting the ABC (as we showed earlier), we can simply register the SortedList
as a collections.Sequence
:
class SortedList: ...collections.Sequence.register(SortedList)
After the class is defined ...
Get Advanced Python 3 Programming Techniques now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.