The setattr() function sets the value of the attribute of an object.
Example
setattr() Syntax
The syntax of the setattr() function is:
setattr(object, name, value)
If you want to get the attribute of an object, use getattr().
setattr() Parameters
The setattr() function takes three parameters:
- object - object whose attribute has to be set
- name - attribute name
- value - value given to the attribute
setattr() Return Value
The setattr() method returns None.
Example 1: How setattr() works in Python?
Output
Before modification: Adam After modification: John
Example 2: When the attribute is not found in setattr()
If the attribute is not found, setattr() creates a new attribute an assigns value to it. However, this is only possible if the object implements the __dict__() method.
You can check all the attributes of an object by using the dir() function.
Output
Name is: John Age is: 23