What is a metaclass in Python?


Metaprogramming in python is defined as the ability of a program to influence itself. It is achieved by using metaclass in python.

Metaclasses in Python

Metaclasses are an OOP concept present in all python code by default. Python provides the functionality to create custom metaclasses by using the keyword type. Type is a metaclass whose instances are classes. Any class created in python is an instance of type metaclass.

The type() function can create classes dynamically as calling type() creates a new instance of type metaclass.

Syntax

Syntax to create a class using type() is given below −

class name = type(⁢name>, ⁢bases>, ⁢dct>

Where,

<⁢name> is the class name

<⁢bases> defines a tuple of bases class from which the class will inherit

<⁢dct> defines namespace dictionary which contains definition of class

Example 1

This is the simplest class definition as both and arguments are empty, hence no inheritance and namespace dictionary is null.

DemoClass = type('DemoClass', (), {}) obj = DemoClass() print(obj)

Output

The output of the above code gives a variable DemoClass which holds the reference to the class.

<__main__.DemoClass object at 0x7fde96524240>

Example 2

In the following example, the second parameter is a tuple with a single element Demo from which class Demo2 inherits.

class Demo: pass Demo2 = type('Demo2', (Demo,), dict(attribute=10)) obj = Demo2() print(obj.attribute) print(obj.__class__) print(obj.__class__.__bases__)

Output

In the output of the above program, printing the attribute gives 10 since it has been stored in parameter. Printing the class gives Demo2 as output as that is the derived class and printing the base class gives Demo as the result since it is present in the parameter.

10
⁢class '__main__.Demo2'>
(⁢class '__main__.Demo'>,)

Example 3

In the following example the <dct>  parameter has an attribute variable and attribute_value which acts as the method of Demo class.

Demo = type('Demo',(), { 'attribute': 10, 'attribute_value': lambda obj : obj.attribute } ) obj = Demo() print(obj.attribute) print(obj.attribute_value())

Output

The above program gives a value of 10 for both instances as attribute has been given a value of 10 in and attribute_value is a method that calls attribute variable which has an assigned value of 10.

10
10

Example 4

In the following example an externally created function is assigned to attribute_value in <dct>  parameter to replace lambda as lambda can only perform simple tasks.

def s(obj): print('Attribute value =', obj.attribute) Demo = type('Demo',(), { 'attribute': 10, 'attribute_value': s } ) object = Demo() print(object.attribute) object.attribute_value()

Output

The output again gives 10 for attribute and attribute_value. Since attribute variable has value of 10, when attribute_value is called it fetches s which is the externally assigned function. The program then executes the function s which runs the print statement for attribute_value.

10
Attribute value = 10

Custom Metaclasses in Python

Python allows the creation of custom metaclasses by passing type as parameter when creating a new class. Metaclasses are also known as class factories as they can be used as template to create classes.

Example to create custom metaclass

In this example MetaClass is a custom metaclass as it inherits from type, which in itself is a metaclass. This allows for creation of __new__() which does the following −

  • Call parent metaclass type through super() to create new class
  • Create custom attribute for the class
  • Return the created class

MetaClass can then act as a template for creation of CustomClass, so CustomClass inherits the attributes of MetaClass.

Example

Following is an example to create custom metaclass −

class MetaClass(type): def __new__(self,name,base,dct): obj = super().__new__(self,name,base,dct) obj.attribute = 10 return obj # MetaClass acts as template for CustomClass class CustomClass(metaclass = MetaClass): pass print(CustomClass.attribute)

Output

Following is an output of the above code−

10

Updated on: 18-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements