Skip to content

Metaclasses and ABCs

Beginning of the lesson

Metaclasses and ABCs

Controlling how classes themselves are built and behave

Big Idea: In Python a class is not a fixed blueprint carved in stone — it is an object that is itself created at runtime by another class called its metaclass. Understanding this lets you hook into class creation to register subclasses, validate interfaces, or inject behaviour. Abstract Base Classes (ABCs) are the everyday, well-lit face of this machinery: they let you declare a contract of required methods and have Python enforce it. Most of the time an ABC or __init_subclass__ is the right tool; a hand-written metaclass is the heavy artillery you reach for rarely and deliberately.
By the end you will be able to:
  • explain the chain instance -> class -> metaclass and why type sits at the top,
  • create a class dynamically with type(name, bases, namespace),
  • use __init_subclass__ to hook subclass creation without a metaclass,
  • define and enforce an interface with abc.ABC and @abstractmethod,
  • write a custom metaclass and, crucially, judge when it actually earns its keep.

1. A class is an object too

You already know every value in Python is an object with a type: type(3) is int, type("hi") is str. The step most developers miss is that this applies to classes themselves. A class is a runtime object, and its type is called its metaclass. By default that metaclass is the built-in type.

class Dog:
    pass

fido = Dog()

print(type(fido))   # <class '__main__.Dog'>
print(type(Dog))    # <class 'type'>
print(type(type))   # <class 'type'>  -- type is its own type

So there is a chain: an instance is an instance of a class, and a class is an instance of a metaclass. Because Dog is itself an object, you can assign it to a variable, store it in a list, add attributes to it, and — the key insight — you can build it programmatically instead of with the class keyword.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers