Skip to content
UPEEC

Metaclasses

The class of a class: metaclasses customise how classes themselves are created.

Expert
Comments 0
class Registry(type):
    plugins = {}
    def __new__(mcls, name, bases, ns):
        cls = super().__new__(mcls, name, bases, ns)
        mcls.plugins[name] = cls
        return cls

class Plugin(metaclass=Registry): pass

Most needs are better met by class decorators or __init_subclass__. Frameworks like Django's ORM use metaclasses.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.