Skip to main content

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
Submitted by devanshi.srivastava on July 15, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.