Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.6 — Metaclasses and Class Creation
Python · Example 1 of 2

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.

01

Use type() to create a class Cat with a sound attribute and a speak method, then call it.

02

Write a base class whose __init_subclass__ raises TypeError unless the subclass defines sides in its own body.

03

Write a class decorator register that appends each decorated class name to a list.

Explain it without notes

01

What is a metaclass, and what is the default one?

02

Explain the order of __new__, __init__ and __call__ when you create a class and when you create an instance.

03

When would you use __init_subclass__ instead of a metaclass?

04

What is a class decorator, and how does it differ from a metaclass?

Metaclass hooks and type() by hand
Sign in to run this example in your browser.

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