setattr() Built-in Function

Python – setattr()

Python setattr() built-in function sets the value for an attribute of an object.

Please note that the object must allow the assignment of the value to the attribute.

In this tutorial, we will learn the syntax and usage of setattr() built-in function with examples.

Syntax

The syntax of setattr() function is

setattr(object, attribute, value)

where

ParameterMandatory/
Optional
Description
objectMandatoryA Python object that allows setting of given attribute.
attributeMandatoryattribute is a string value.
valueMandatoryAny arbitrary value.

Examples

1. Set attribute for a class object

In the following program, we define a class named Student. This class has three attributes: name, age, and country.

We create an object of class type Student, and print the details. Then we set attributes of this class object using setattr() built-in function and then print the details again.

Python Program

class Student:
    name = 'Name'
    age = 0
    country = 'NA'

    def __str__(self):
     return self.name + " aged " + str(self.age) + " from " + self.country 

student1 = Student()
print(student1)

setattr(student1, 'name', 'Mike')
setattr(student1, 'age', 12)
setattr(student1, 'country', 'Canada')

print(student1)

Output

Name aged 0 from NA
Mike aged 12 from Canada

Related Tutorials

  • Python getattr() This built-in function gets the value of an attribute of an object.
  • Python hasattr() This built-in function checks if the object has the specified attribute.
  • Python delattr() This built-in function deletes the attribute from an object.

Summary

In this Built-in Functions tutorial, we learned the syntax of the setattr() built-in function, and how to use this function to set the attribute of an object with a value.