Python: Metaclasses

A class is also an object, and just like any other object it’s a instance of something called Metaclass. A special class type creates these Class object. The type class is default metaclass which is responsible for making classes.

A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave.

Metaclass is responsible for generation of classes, so we can write our own custom metaclasses to modify the way classes are generated by performing extra actions or injecting code. Usually we do not need custom metaclasses but sometime it’s necessary. 

Example:

class func:
    pass

func.a = 20
func.abc = lambda self: print("a =",9*2)
 
object = func()
 
print(func.a)
object.abc()

Output:

20
a= 18
Tags