
Understanding Python Classes
In Python, everything is an object and every object has a type — including primitives, functions, and classes themselves. type() and __class__ reveal this relationship.
Tag
61 posts

In Python, everything is an object and every object has a type — including primitives, functions, and classes themselves. type() and __class__ reveal this relationship.

Which method runs when in Python metaclasses? The execution order of __prepare__, __new__, __init__, and __call__ during class definition and instance creation.

The execution order of metaclass methods together with their full argument lists. Follow step by step which values arrive at each method.

A more complete metaclass implementation without deriving from type: a two-phase lifecycle managed by __call__, and delegation of __str__ and attribute access to the namespace.
![namespace['attr'] = 1](/images/posts/understanding-python-classes.png)
To see how Python truly processes a class statement: get a namespace with type.__prepare__, execute the body with exec, then build the class with type().

A metaclass is a class whose instances are classes. Just as type produces classes like int or str, a custom metaclass produces its own classes in the same way.

Is it possible to write a metaclass without deriving from type? Yes — but what you end up with is not a real Python class; it is an instance of Meta.

Every class in Python has a metaclass. If you don't specify one explicitly, type steps in as the default — invisible, but always there.

Two ways to implement the Singleton pattern with a metaclass in Python — and the critical difference between them: in one, subclasses are separate objects; in the other, they are the same object.