setattr() Built-in Function

Python – setattr()

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

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


The syntax of setattr() function is

setattr(object, attribute, value)


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

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


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 + " aged " + str(self.age) + " from " + 

student1 = Student()

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

Run Code Copy


Name aged 0 from NA
Mike aged 12 from Canada
  • 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.


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.

Code copied to clipboard successfully 👍