- How to dynamically add new attributes to a class in python ?
- Create a python class
- Create a python class that can add new attributes
- References
- Benjamin
- Python add field to object
- # Table of Contents
- # Add attributes to an Object in Python
- # Add attribute to an Object using dot notation
- # Add multiple attributes to an object using a for loop
- # Add attributes to an Object using SimpleNamespace()
- # Additional Resources
- Add Attribute to Object in Python
- Add Attribute to Object in Python
- Related Article — Python Object
How to dynamically add new attributes to a class in python ?
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')
product_01.data
product_01.name
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:
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
array([ 1, 4, 9, 16, 25, 36, 49, 64])
References
Benjamin
Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.
Skills
Python add field to object
Last updated: Feb 22, 2023
Reading time · 3 min
# Table of Contents
# Add attributes to an Object in Python
Use the setattr() function to add attributes to an object, e.g. setattr(obj, ‘name’, ‘value’) .
The setattr function takes an object, the name of the attribute and its value as arguments and adds the specified attribute to the object.
Copied!class Employee(): def __init__(self, name): self.name = name emp1 = Employee('bobby') setattr(emp1, 'salary', 100) setattr(emp1, 'age', 30) print(getattr(emp1, 'salary')) # 👉️ 100 print(getattr(emp1, 'age')) # 👉️ 30 print(getattr(emp1, 'name')) # 👉️ bobby
We instantiated the Employee() class and used the setattr() function to add attributes to the object.
The setattr function adds an attribute to an object.
The function takes the following 3 arguments:
Name | Description |
---|---|
object | the object to which the attribute is added |
name | the name of the attribute |
value | the value of the attribute |
The name string may be an existing or a new attribute.
If you need to create a generic object, use the pass statement in a class.
Copied!class GenericClass(): pass obj1 = GenericClass() setattr(obj1, 'salary', 100) setattr(obj1, 'age', 30) print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'age')) # 👉️ 30
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
Make sure your class does not extend from the built-in object class.
The object class doesn’t have a __dict__ attribute, therefore we can’t assign attributes to an instance of the class.
# Add attribute to an Object using dot notation
You can also use dot notation to add an attribute to an object.
Copied!class GenericClass(): pass obj1 = GenericClass() obj1.salary = 100 obj1.age = 30 print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'age')) # 👉️ 30 print(obj1.salary) # 👉️ 100 print(obj1.age) # 👉️ 30
Using dot notation is equivalent to using the setattr() method.
However, when using dot notation, you might get linting warnings for defining attributes outside of the _ _ init _ _ () method.
# Add multiple attributes to an object using a for loop
You can use a for loop if you need to add multiple attributes to an object.
Copied!class GenericClass(): pass my_dict = 'name': 'bobbyhadz', 'age': 30> obj1 = GenericClass() for key, value in my_dict.items(): setattr(obj1, key, value) print(getattr(obj1, 'name')) # 👉️ bobbyhadz print(getattr(obj1, 'age')) # 👉️ 30
We used a for loop to iterate over a dictionary’s items and added the key-value pairs as attributes to the object.
If you have to use the setattr method from within a class method, you would pass self as the first argument.
Copied!class GenericClass(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, key, value) my_dict = 'name': 'bobbyhadz', 'age': 30> obj1 = GenericClass(my_dict) print(getattr(obj1, 'name')) # 👉️ bobbyhadz print(getattr(obj1, 'age')) # 👉️ 30
You can also use the SimpleNamespace class if you need to create a generic object to which you can add attributes.
# Add attributes to an Object using SimpleNamespace()
This is a two-step process:
- Use the SimpleNamespace class to create an object.
- Use the setattr() function to add attributes to the object.
Copied!from types import SimpleNamespace obj1 = SimpleNamespace() setattr(obj1, 'salary', 100) setattr(obj1, 'language', 'Python') print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'language')) # 👉️ Python print(obj1) # 👉️ namespace(salary=100, language='Python')
The SimpleNamespace class is a subclass of object and provides attribute access to its namespace.
We can’t add attributes to instances of the built-in object class, however, we can attributes to instances of the SimpleNamespace class.
The class can also be initialized with keyword arguments.
Copied!from types import SimpleNamespace obj1 = SimpleNamespace(name='bobby', age=30) setattr(obj1, 'salary', 100) setattr(obj1, 'language', 'Python') print(getattr(obj1, 'salary')) # 👉️ 100 print(getattr(obj1, 'language')) # 👉️ Python print(getattr(obj1, 'name')) # 👉️ bobby print(getattr(obj1, 'age')) # 👉️ 30 # 👇️ namespace(name='bobby', age=30, salary=100, language='Python') print(obj1)
The SimpleNamespace class is quite convenient when you need to create a blank object to which you can add attributes.
Attributes cannot be added to the built-in object class, so the SimpleNamespace should be your preferred approach.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Add Attribute to Object in Python
We will introduce how to add an attribute to an object in Python. We will also introduce how we can change the attributes of an object in Python with examples.
Add Attribute to Object in Python
In Python, we work with objects now and then because Python is an Object-oriented language. Objects make our coding reusable and easy to implement complex structures.
The main part of objects is their attributes. Attributes define what the properties of a certain object are.
While working with objects, there may be many situations where we need to add a new attribute to an object in the middle of the program.
Python provides a function setattr() that can easily set the new attribute of an object. This function can even replace the value of the attribute.
It is a function with the help of which we can assign the value of attributes of the object.
This method will provide us with many ways to allocate values to variables by certain constructors and object functions. By using this function, we will also be able to have other substitutive ways to assign value.
Now, let’s discuss the structure of this setattr() function. The structure which constructs a setattr() is shown below.
# python setattr(object, name, value)
As you can see from the syntax of this function, we pass three arguments into the function, and it will then allow us to set the attributes of an object.
- Object — We will pass the object’s name we created and want to set attributes for.
- Name — It will be the name of the attribute of that object that we want to assign value to.
- Value — We will pass the attribute value here.
Let’s go through an example in which we will create a class of students. We will create a new student and assign it some attributes, as shown below.
# python class Students(): name = "Rana Hasnain" roll_no = "BC140402269" cgpa = 3.5 new_student = Students() setattr(new_student, 'name', 'James Bond') setattr(new_student, 'roll_no', '007') setattr(new_student, 'cgpa', 4) print("New Student Name:",new_student.name) print("New Student Roll #:",new_student.roll_no) print("New Student Cgpa:",new_student.cgpa)
As you can see from the above example, it was quite easy to set the object’s attributes that we created. Now, let’s discuss a different scenario.
Let’s suppose we have a new object and want to set an attribute missing from the class.
In some cases, there are no attributes, or all attributes are not created in a class. When this happens, we assign a new attribute and can set a value for it.
But to make it happen, the object should implement the __dict__() method. Let’s go through an example and try to assign values to an attribute that doesn’t exist.
We will use the above example and try to assign a new attribute, degree , as shown below.
# python class Students(): name = "Rana Hasnain" roll_no = "BC140402269" cgpa = 3.5 new_student = Students() setattr(new_student, 'name', 'James Bond') setattr(new_student, 'roll_no', '007') setattr(new_student, 'cgpa', 4) setattr(new_student, 'degree', 'BSCS') print("New Student Name:",new_student.name) print("New Student Roll #:",new_student.roll_no) print("New Student Cgpa:",new_student.cgpa) print("New Student Degree:",new_student.degree)
As you can see from the above example, this function can also create new attributes that don’t exist and assign values to them.
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.