Python metaclass

Filed Under: Python

Welcome to today’s tutorial on python metaclass. We all know that python is an object oriented programming language which means it binds datas with functionalities i.e. class. Before starting about python metaclass we hope you know the concept of class and inheritance. If you don’t have the idea, then you can learn python class and python inheritance first.

Python Metaclass

Python metaclass is a class that instantiates a class. In python, a class is actually an object of another class. This another class is called metaclass. Metaclass in python defines the behaviors of class objects. let’s look at some examples to understand the metaclass concept clearly.

Python built-in Metaclass

type is a built in metaclass in python. Let’s start with the following example:


class SampleClass():
   pass
obj = SampleClass()
print(type(obj))

In the above code we have created a class named SampleClass, and creating an object of it. Then type of object says:


class '__main__.SampleClass'

That means obj is an object of SampleClass. Now if we try to see the type of SampleClass itself as following:


print(type(SampleClass))

Then the output is:


class 'type'

That means SampleClass is an object of class type. To be more specific SampleClass is an instance of class type. So type is a metaclass. Every class of python belongs to the built-in metaclass type.

How python metaclass works?

Whenever we create any class then the default metaclass gets called. This metaclass gets called with three information – name of the class, set of base classes of the class and the attributes of the class.

As type is the builtin metaclass, whenever we create a class type gets called with these three argument.

We are saying that every class in python is also a object of type, which means we can create any class in a single line just like we create object of any class. This way of creating a class is called “creating class on the fly”.

Create python Class using metaclass

So using the metaclass type, you can create your class in a single line by calling as following:


Student = type('Student', (), {})

This will create a class named Student at run time of the code. The above line is equivalent to the following code:


class Student:
   pass

If inherits some other class say for example Department then we write as following,


class Student(Department):
   pass

Inherited classes should be provided in the second argument when creating class on the fly,


Student = type('Student', (Department,), {})

If Student class contains some attributes and functions then they should be provided in the 3rd argument as key value pair. See following the examples:


class Student:
  
   def __init__(self, name, roll):
       self.name = name
       self.roll = roll
       self.marks = 0.0

Those attributes and functions can be added as following:


def init(self, name, roll):
   self.name = name
   self.roll = roll
   self.marks = 0.0


Student = type('Student', (), {'__init__' : init})

Notice that we have defined the function before we use it. One more thing I want you to understand is that the first argument is class name. So if you write as following:


Student = type('StudentClass', (), {'__init__' : init})
obj = Student("Zinia", "59")
print(obj.__class__)

Then the output will be,


class '__main__.StudentClass'

So, it’s better to keep the same name for class and variable to keep consistency.

Set the metaclass

You can set your class’s metaclass explicitly. Whenever python gets the keyword class then it searches for the metaclass. If not found then the default metaclass type is used to create the object of the class. You can set metaclass of your class using the __metaclass__ attribute as following:


class SomeClass:
   __metaclass__ = type
   # other methods...

print(SomeClass.__metaclass__)

It will produce output as;


class 'type'

Creating Metaclass in Python

Finally, you can also create your own metaclass to define the behaviour of any class that are created using your class.

To do that your class must inherit the default metaclass type as this is the main metaclass. See the following example:

python metaclass

It will output:
metaclass in python

Python metaclass is a very complicated topic. Here we have given the basic idea of metaclass. Hope now, you do understand the basic concept of metaclass. To understand the functionalities of metaclass you have to go very deep. However you should be aware of how python classes work and what is the role of metaclass in python.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages