How to dynamically add new attributes to a class in python ?

Published: July 18, 2021

Tags: Python; Class;

DMCA.com Protection Status

Example of how to dynamically add new attributes to a class in python:

Create a python class

Lets first create a simple class in python called here product with two atrributes data and name:

class product:

        def __init__(self, data, name, **kwargs):

                self.data = data        
                self.name = name

Now lets create an instance of class:

import numpy as np

data = np.arange(1,9)

product_01 = product(data, '01')

then

product_01.data
product_01.name

returns respectively

[1 2 3 4 5 6 7 8]

and

'01'

Lets assume now that we want to add a new attibute called "new_data" to the instance of class "product_01" that will store the following data:

data_02 = data ** 2

Create a python class that can add new attributes

To do that, a solution is to use setattr when
the class is defined:

class product:

        def __init__(self, data, name, **kwargs):

                self.data = data        
                self.name = name

        def adding_new_attr(self, attr):
                setattr(self, attr, attr)

then to add the new attribute called for example "new_data" just do:

setattr(product_01, "new_data", data_02)

product_01.new_data

returns here

array([ 1,  4,  9, 16, 25, 36, 49, 64])

References