Python setattr() Function

Python setattr() function is used to set the value of an attribute for a given object. This function gives you an alternative to assign the attribute value without using the dot(.) operator.

If the attribute already exists, the setattr() function updates its existing value, otherwise, it creates a new attribute under that object and assigns the given value to it.

class Student:
    name = 'John'

student = Student()

# Set 'age' attribute to 23
setattr(student, 'age', 23)    

print('Student name: ', student.name)
print('Student age: ', student.age)

# Output
# Student name:  John
# Student age:  23

setattr() Syntax

The syntax of the setattr() function is as follows:

setattr(object, attribute, value)

setattr() Parameters

The setattr() function takes in three parameters:

  • object – The target object whose attribute has to be set
  • attribute – Name of the attribute to be set
  • value – The value of the attribute

setattr() Return Value

The setattr() function returns the None object.


Python setattr() Examples

In the example below, we have created a class named Student. This Student class has only one attribute ‘name’. Therefore, by default, all of its objects will have only and only one attribute i.e ‘name’.

Now suppose you want to add some additional information to any individual student. You can simply achieve this using the setattr() function.

In the example below, we have added an extra attribute ‘age’ to the student object using the setattr() function.

Example 1: Set object attributes using setattr()

class Student:
    name = 'John'

student = Student()

# Set 'age' attribute to 23
setattr(student, 'age', 23)    

print('Student name: ', student.name)
print('Student age: ', student.age)

Output:

Student name:  John
Student age:  23

Example 2: Set class attributes using setattr()

The setattr() function is not just restricted to objects. It can also be used to set class attributes. This is very helpful in situations where we need to add the same attribute to each object of the class.

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age  = age

student1 = Student('John', 23)
student2 = Student('James', 24)

# Set 'section' attribute to 'D' for class Student
setattr(Student, 'section', 'D')    

print('Student1 name: ', student1.name)
print('Student1 age: ', student1.age)
print('Student1 section: ', student1.section)

print('nStudent2 name: ', student2.name)
print('Student2 age: ', student2.age)
print('Student2 section: ', student2.section)

Output:

Student1 name:  John
Student1 age:  23
Student1 section:  D

Student2 name:  James
Student2 age:  24
Student2 section:  D

Python setattr() vs Regular Assignment

At the beginning of this tutorial, we learned that the setattr() function is an alternative to the regular assignment using the dot(.) operator. I mean to say that we can set or modify a class or object attribute using the dot(.) operator. If it is so then why do we use the setattr() function?

Well, using regular assignments we can set only static attributes, but not user-defined.

In the example below, we are trying to set a new user-defined attribute to the student object. Let’s see if it works.

Example 1: The problem with regular assignment

class Student:
    name = 'John'
 
student = Student()

attrName  = input('Enter attribute name: ')
attrValue = input('Enter attribute value: ') 

student.attrName = attrValue

print('Student name: ', student.name)
print('Student age: ', student.age)

Output:

Enter attribute name: age
Enter attribute value: 24
Student name:  John
Traceback (most recent call last):
  File "<string>", line 13, in <module>
AttributeError: 'Student' object has no attribute 'age'

Damn! It didn’t work. But why? This is because the assignment student.attrName = attrValue sets a new attribute named ‘attrName’ on the student object not ‘age’ that we were expecting. Now because the ‘age’ attribute does not exist therefore we got the AttributeError.


Example 2: Solution to the above problem

A simple solution to the above problem is using the setattr() function instead of the regular assignment using the dot(.) operator. Just look at the example below:

class Student:
    name = 'John'
 
student = Student()

attrName  = input('Enter attribute name: ')
attrValue = input('Enter attribute value: ') 

setattr(student, attrName, attrValue)

print('Student name: ', student.name)
print('Student age: ', student.age)

Output:

Enter attribute name: age
Enter attribute value: 24
Student name:  John
Student age:  24

It works!!! I hope now you got the idea what are the benefits of using setattr() over the regular assignment.


Recommended Articles

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.