How to Add Attributes in Python Metaclass?
Last Updated :
26 Apr, 2025
This article explains what a metaclass is in the Python programming language and how to add attributes to a Python metaclass. First, let’s understand what a metaclass is. This is a reasonably advanced Python topic and the following prerequisites are expected
To understand metaclasses, you need to understand Python classes. In most languages, a class is just a blueprint that describes how objects are created. In Python, classes are much more than that. Not only do classes define how instances are created, Python classes themselves are objects. Since classes are objects in Python, they are instances of a special class called metaclass and all metaclasses are instances of type class that create these class objects. Type class is the default metaclass responsible for creating classes. In simple words, Python objects are instances of a class and classes are instances of a metaclass. The following diagram summarizes this idea.
When to use a Metaclass
- If a class is defined and no metaclass is provided, the default type metaclass is used. If metaclass is specified then the base class is not an instance of type(), it will be used directly as the type for the base class.
- If you want your class to change automatically on creation, use a metaclass.
Below is a simple demonstration of how attributes can be defined and added to a Metaclass in Python.
Creating a Metaclass
To add attributes to a metaclass in Python first we need to create a metaclass, in Python, we create a metaclass in the same way as a normal class which inherits a type class. Here, a metaclass named DemoMetaClass is created which inherits the type class as shown code below:
Python3
class DemoMetaClass( type ):
attr1 = 1
def __new__( cls , name, base, defcl):
obj = super ().__new__( cls , name, base, defcl)
obj.attr2 = 2
return obj
|
- __new__(): A method called before __init__(). Creates and returns an object.
- cls: It refers to the class on which __new__ is called in.
- name: Refer to the name of the class.
- base: It is the parent class of the given class.
- defcl: It specifies some definitions for the class.
Adding Attributes to Created Metaclass
Now that we have created a metaclass called DemoMetaClass and defined attr1 and atrr2 attributes while defining it, let’s create a base class that is an instance of that metaclass. As you can see we have created 2 classes first one is a default class Student and the second is Demo with metaclass as DemoMetaCLass.
Python3
class Student():
pass
class Demo(metaclass = DemoMetaClass):
pass
print ( "Student class is instance of " , type (Student))
print ( "Demo class is instance of " , type (Demo), end = "\n\n" )
print (f "DemoMetaClass \nattr1 => {Demo.attr1} \nattr2 => {Demo.attr2}\n" )
|
Output:
The below image shows that by default the metaclass is a type class as in the case of the Student class while in the case of Demo the metaclass is DemoMetaClass, As Demo is the base class of DemoMetaClass it also possesses attributes of its metaclass, which is printed in the output.
Adding a new attribute
We can also add attributes to the metaclass as we do with the usual class in Python, As you can see in the output above a new attribute named attr3 with value 3 is been added to DemoMetaClass.
Python3
DemoMetaClass.attr3 = 3
print (f "DemoMetaClass \nattr1= > {Demo.attr1} \nattr2 = > {Demo.attr2}\nattr3= > {Demo.attr3}" )
|
Output:
Complete Code
Python3
class DemoMetaClass( type ):
attr1 = 1
def __new__( cls , name, base, defcl):
obj = super ().__new__( cls , name, base, defcl)
obj.attr2 = 2
return obj
class Student():
pass
class Demo(metaclass = DemoMetaClass):
pass
print ( "Student class is instance of " , type (Student))
print ( "Demo class is instance of " , type (Demo), end = "\n\n" )
print (f "DemoMetaClass \nattr1 => {Demo.attr1} \nattr2 => {Demo.attr2}\n" )
DemoMetaClass.attr3 = 3
print (
f "DemoMetaClass \nattr1 => {Demo.attr1} \nattr2 => {Demo.attr2}\nattr3 => {Demo.attr3}" )
|
Output:
Student class is instance of <class 'type'>
Demo class is instance of <class '__main__.DemoMetaClass'>
DemoMetaClass
attr1 => 1
attr2 => 2
DemoMetaClass
attr1 => 1
attr2 => 2
attr3 => 3
Similar Reads
How to Print Object Attributes in Python
In Python, objects are the cornerstone of its object-oriented programming paradigm. An object is an instance of a class, and it encapsulates both data (attributes) and behaviors (methods). Understanding how to access and print the attributes of an object is fundamental for debugging, inspecting, and
2 min read
How to Get a List of Class Attributes in Python?
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
4 min read
How to Change Class Attributes in Python
In Python, editing class attributes involves modifying the characteristics or properties associated with a class. Class attributes are shared by all instances of the class and play an important role in defining the behavior and state of objects within the class. In this article, we will explore diff
3 min read
How to Access dict Attribute in Python
In Python, A dictionary is a type of data structure that may be used to hold collections of key-value pairs. A dictionary's keys are connected with specific values, and you can access these values by using the keys. When working with dictionaries, accessing dictionary attributes is a basic function
6 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
2 min read
How to create modules in Python 3 ?
Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using t
4 min read
Accessing Attributes and Methods in Python
In Python, attributes and methods define an object's behavior and encapsulate data within a class. Attributes represent the properties or characteristics of an object, while methods define the actions or behaviors that an object can perform. Understanding how to access and manipulate both attributes
4 min read
How to use NamedTuple and Dataclass in Python?
We have all worked with classes and objects for more than once while coding. But have you ever wondered how to create a class other than the naive methods we have all been taught. Don't worry in this article we are going to cover these alternate methods. There are two alternative ways to construct a
2 min read
How to add Elements to a List in Python
In Python, adding elements to a list is a common operation that can be done in several ways. One of the simplest methods is using the append() method. In this article we are going to explore different methods to add elements in the list. Below is a simple Python program to add elements to a list usi
3 min read
Python | PIL Attributes
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. Attributes: Attribute defines the various property of an object, element or file. In the image, attribute refers to the size, filename, format or mode, etc. of the image. Image used is: Instances
2 min read