Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 14 / Topic 6 of 11

Class creation

A class is an object too, and its type is type. A class that makes classes is a metaclass; type is the default metaclass. When Python runs a class block, it collects the names into a dict and then calls type(name, bases, namespace). Think of a factory that makes cookie cutters: cookie cutters (classes) make cookies (objects), and the factory (type) makes cookie cutters.

type() makes classes

def describe(self):
    return f"{self.name} costs ₹{self.price:,}"

Gadget = type("Gadget", (), {"kind": "gadget", "describe": describe})
# the same as: class Gadget: kind = "gadget"; describe = describe

phone = Gadget()
phone.name, phone.price = "Phone", 14999
print(Gadget.kind, "|", phone.describe())     # gadget | Phone costs ₹14,999
print(type(Gadget).__name__, type(type).__name__)   # type type

Class decorators

A class decorator is like a function decorator (Part 10), but it receives the class, changes or registers it, and returns it.

def add_summary(cls):
    def summary(self):
        return f"{cls.__name__}{vars(self)}"
    cls.summary = summary                     # add a method to the class
    return cls

@add_summary
class Invoice:
    def __init__(self, number, amount):
        self.number, self.amount = number, amount

print(Invoice("INV-7", 1760).summary())   # Invoice{'number': 'INV-7', 'amount': 1760}

__init_subclass__: a plugin registry

__init_subclass__ is a class method on a parent class that Python calls each time a child class is created. It is perfect for a plugin registry: a dict where every subclass adds itself, so new features plug in without editing the old code.

class Notifier:
    registry = {}

    def __init_subclass__(cls, channel, **kwargs):
        super().__init_subclass__(**kwargs)
        Notifier.registry[channel] = cls          # register the new class

class SmsNotifier(Notifier, channel="sms"):
    def send(self, to, text):
        return f"SMS to {to}: {text}"

class EmailNotifier(Notifier, channel="email"):
    def send(self, to, text):
        return f"Email to {to}: {text}"

print(list(Notifier.registry))                    # ['sms', 'email']
notifier = Notifier.registry["sms"]()             # pick the plugin by name
print(notifier.send("98xxxxxx01", "Order 101 shipped"))
# SMS to 98xxxxxx01: Order 101 shipped

Adding WhatsApp later means writing one new class; registry and the calling code stay the same.

Metaclasses, briefly (and when NOT to use them)

A custom metaclass is a subclass of type. Its __new__ runs when a class is created.

class LoggingMeta(type):
    def __new__(mcls, name, bases, namespace):
        print(f"creating class {name}")
        return super().__new__(mcls, name, bases, namespace)

class Report(metaclass=LoggingMeta):     # prints: creating class Report
    pass

print(type(Report).__name__)             # LoggingMeta

Reach for the simplest tool that works:

Need Use
check or compute one attribute @property or a descriptor
change or register one class a class decorator
do something for every subclass __init_subclass__
change how classes themselves behave (rare, framework code) a metaclass

🔍 Going deeper: "Metaclasses are deeper magic than 99% of users should ever worry about" (Tim Peters). Two different metaclasses in one inheritance tree cause a conflict error, another reason to prefer __init_subclass__.

Full program: examples/05_class_creation.py.

Done here? The practice set for Part 14 — 8 exercises with solutions — is on the part page.

Search the guide