What is Metaclass in Python

Hello coders. In this post, we will learn what is a metaclass in Python? In Python, there is metaprogramming of classes that is known with the name of a metaclass.

Metaprogramming is a technique of programming in which program uses other programs as its data. In metaprogramming, the program has the power to manipulate itself. The metaclass is the concept of OOPs(Object Oriented Programmings). We knowingly or unknowingly use the metaclass.

Also read: Adding attributes in Python metaclass

So let’s begin the concept of metaclasses in Python.

Metaclass is Python

Before knowing about Python metaclasses you must be aware of object-oriented programming in Python. In Python or in any other language we have a type for every variable or object we declare. For getting type of anything(variable,object,etc.) in Python we can use type() function.

dict={}
print(type(dict))

list=[]
print(type(list))

str=" "
print(type(str))

Output:

<class 'dict'>
<class 'list'>
<class 'str'>

So we can see that every type in Python has a class. Like the dictionary is the object of dict class, the list is the object of list class and so on. If we want to create a new type we have to just create a class of that name.

class example:
    pass

obj=example()
print(type(obj))

Output:

<class '__main__.example'>

A class is also an object, and it is an instance of a metaclass. The responsibility of making these classes is of default metaclass type. For the above code, the output of the example class will be a type.

class example:
    pass

obj=example()
print(type(example))

Output:

<class 'type'>

Summarizing all we can say that Metaclass creates class and class creates objects. The metaclass is liable for the creation of classes, so for changing the way of class creation we can use our custom metaclass by adding extra codes.

Creating Metaclass

Bypassing the metaclass keyword in the class definition we can customize the class creation process.

class meta(type):
    pass

class baseclass(metaclass=meta):
    pass

class derivedclass(baseclass):
    pass

print(type(meta))
print(type(baseclass))
print(type(derivedclass))

Output:

<class 'type'>
<class '__main__.meta'>
<class '__main__.meta'>

When defining a new class if no metaclass is defined the default type metaclass is used. If a given metaclass is not the object(instance) of type(), in that situation it is used directly as a metaclass.

The metaclass is harder to understand, 99% of programmer should never worry about. If you are thinking whether you need them during programming, then I think you don’t need it(leaving exception).

In this post, we learn the use of metaclass and how to implement it. For a tutorial on any Python topic please comment below the topic name.

Thank You.

 

Leave a Reply

Your email address will not be published. Required fields are marked *