Python Metaclass

Learn about what is Metaclass in Python, the Type Metaclass, custom Metaclass and the comparison between Metaclass and Inheritance

Photo by Grace O’Driscoll on Unsplash
>>> class Example:
... pass
>>> e = Example()
>>> e.__class__
<class '__main__.Example'>
>>> type(e)
<class '__main__.Example'>
>>> e.__class__ is type(Example)
True

Type Metaclass

1. with name arg>>> Example = type('Example', (), {})

>>> x = Example()
>>> x
<__main__.Example object at 0x1088c78e0>
2. with name and base (As tuple)and dict>>> AnotherExample = type('AnotherExample', (Example,), dict(attr=1))

>>> x = AnotherExample()
>>> x.attr
1
>>> x.__class__
<class '__main__.AnotherExample'>
>>> x.__class__.__bases__
(<class '__main__.Example'>,)

How does Metaclass work


>>> __metaclass__ = type
>>>
>>> class A:
... pass
>>> a = A()

>>> a
<__main__.A object at 0x4f5cf3>
>>> type(a)
<class '__main__.A'>
>>> A
<class '__main__.A'>
>>> type(A)
<type 'type'>
class ExampleMeta(type): @classmethod
def __prepare__(metacls, cls, bases):
print(f”Metacls: {metacls} \n cls: {cls} \n bases: {bases}\n”)
print(f”Calling __prepare__ method of {super()}\n”)
return super().__prepare__(cls, bases)
def __new__(metacls, cls, bases, dict):
print(f”Calling __new__ method of {super()}\n”)
return super().__new__(metacls, cls, bases, dict)
def __init__(self, cls, bases, dict):
print(f”Calling __init__ method of {super()}\n”)
super().__init__(cls, bases,dict)

def __call__(self, *args, **kwargs):
print(f”Calling __call__ method of {super()}\n”)
return super().__call__(*args, **kwargs)
class A(metaclass=ExampleMeta):
def __init__(self):
print(“This is when the new class instance gets created\n”)
print(f”Calling __init__ method of {self}”)
===============>AFTER EXECUTION OF ABOVE
Metacls: <class '__main__.ExampleMeta'>
cls: A
bases: ()
Calling __prepare__ method of <super: <class 'ExampleMeta'>, <ExampleMeta object>>Calling __new__ method of <super: <class 'ExampleMeta'>, <ExampleMeta object>>Calling __init__ method of <super: <class 'ExampleMeta'>, <ExampleMeta object>>----------------------------------------------------------a = A()
===============>AFTER EXECUTION OF ABOVE
Calling __call__ method of <super: <class 'ExampleMeta'>, <ExampleMeta object>>This is when the new class instance gets createdCalling __init__ method of <__main__.A object at 0x7f1160225d60>

Metaclass vs. Inheritance

         metaclass                  metaclass
^ ^
| |
instance instance
| |
class B ---inheritance--> class A
^ ^
| |
instance instance
| |
b a

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store