Metaclass hooks and type() by hand
A class is an object made by another object, type. Knowing how class statements call type(name, bases, namespace) explains metaclasses, but most needs are met more simply by __init_subclass__ and class decorators.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use type() to create a class Cat with a sound attribute and a speak method, then call it.
Write a base class whose __init_subclass__ raises TypeError unless the subclass defines sides in its own body.
Write a class decorator register that appends each decorated class name to a list.
Explain it without notes
What is a metaclass, and what is the default one?
Explain the order of __new__, __init__ and __call__ when you create a class and when you create an instance.
When would you use __init_subclass__ instead of a metaclass?
What is a class decorator, and how does it differ from a metaclass?
Expected output
Meta.__new__ builds the class Base
Meta.__init__ finishes the class Base
-- class statement finished --
Meta.__call__ makes an instance of Base
Base.__new__ allocates the instance
Base.__init__ fills it in
Meta Meta type
Woof Dog