Metaclasses In Python

Metaclasses In Python
A metaclass is used to add an intermediate layer to the class creation process. Any class that derives from type can be a metaclass; type itself is Python’s default metaclass.
class Meta(type):
pass
class Example(metaclass=Meta):
attr = 1
def method(self):
return "method"
print(f"{Meta.__class__=}") # <class 'type'>
print(f"{Example.__class__=}") # <class '__main__.Meta'>
print(f"{Example().__class__=}") # <class '__main__.Example'>
print(f"{Example().attr=}") # 1
print(f"{Example().method()=}") # 'method'
assert isinstance(Meta, type)
assert isinstance(Example, Meta)
assert isinstance(Example(), Example)What Does the Output Tell Us?
Meta.__class__→<class 'type'>— Meta itself is an instance oftype; that is, Meta is a class, so its type istype.Example.__class__→<class '__main__.Meta'>— Example is now created byMetarather thantype; its type isMeta.Example().__class__→<class '__main__.Example'>— ordinary instances return their own class as expected.
The assert Lines
assert isinstance(Meta, type) # Meta is an instance of type (Meta is a class)
assert isinstance(Example, Meta) # Example is an instance of Meta (Meta is a metaclass)
assert isinstance(Example(), Example) # Instances are instances of their own classAnalogy
The relationship type → int is identical to the relationship Meta → Example:
typeis used to create theintclass;int’s type istype.Metais used to create theExampleclass;Example’s type isMeta.
This is where a metaclass becomes useful: by overriding Meta.__new__, Meta.__init__, or Meta.__call__ during class creation, you can change the class-definition behavior.
Hakan Çelik
