How to add attributes in Python metaclass

This tutorial will teach you how to add attributes in python metaclass. As we all know in python an object is an instance of a class. In the same way, a class is an instance of a metaclass. Normally, in python, every class that we define is by default, an instance of metaclass type but we can also create custom metaclasses and add attributes for them in python. Let’s see how.

How to add attributes in Python metaclass

Let’s first create a python metaclass. To create a metaclass in python, we need to do the following:

  • Define a class that derives from ‘type’ class. Since type is a metaclass, the defined class will also be a metaclass. To understand how to derive a class from another, read this: Creating Subclass in Python
  • Override _new_ () as shown in the below example code.

Example code:

class MetaClass(type):
   value1 = 5
   def __new__(cls, name, bases, dct):
         x = super().__new__(cls, name, bases, dct)
         x.value2 = 6
         return x

In the above code, first, we create MetaClass that derives from the class ‘type’ and then we override the _new_() method of ‘type’ and add attributes value1 and value2 as shown.

In the _new_() method we have ‘cls’ which implies that the method _new_() belongs to the specified class. After that, we have three parameters that are:

  • name: It’s for the name of the class.
  • bases: It’s for parent classes of the given class in the first parameter.
  • dct: It specifies some definition for the class.

Now that we have created a metaclass with the name MetaClass and defined attributes value1 and value2 for it, let’s create a class which is an instance of this metaclass. See the code below.

class A(metaclass= MetaClass):

Yes, we use the keyword “metaclass” to specify that class A is an instance of MetaClass. The pass keyword specifies that there is nothing in the body of the class.

Now as you can see below we can access the attributes of MetaClass value1 and value2 using class A.


The output is:


We can also add attributes for MetaClass as we do for regular classes in python. See the code here.




Note that we cannot add attributes directly to the metaclass type. When we try to do so, it throws an error as shown.



 File "", line 17, in <module>
TypeError: can't set attributes of built-in/extension type 'type'

Thank you.

Leave a Reply

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