Python setattr() function

overview of setattr()

The setattr() function is used to set the value of an attribute of a given object. To get the value of the attribute of an object, use the getattr() function.

use of setattr()

The setattr() function is used to change the attribute value of a given object. # use of setattr() function to change attribute class Dog: name = 'Rex' rex = Dog() print(rex.name) setattr(rex, 'name', 'Rex2') print(rex.name) A new class object is created and the name is printed as Rex. Then the attribute name is changed to Rex2 and the same attribute is printed again. Rex Rex2

syntax of setattr()

The syntax of the setattr() function is: setattr(object, name, value)

arguments of setattr()

The setattr() accepts three arguments, and all three are required.
argument required description
object required the object, whose attributes are to be changed
name required the attribute name to be changed
value required the new attribute value
If the specified attribute is not found, a new attribute value is created. If any other number of arguments are passed to the setattr() function, a TypeError exception is raised. TypeError: setattr expected 3 arguments, got 2

return values of setattr()

The setattr() functions returns None. The specified attributes of the given object are changed.



Click to jump to section