The setattr() function in Python is used to set the value of a named attribute of an object. It takes three parameters:
setattr(obj, name, value)
where,
- obj: the object whose attribute is to be set.
- name: the name of the attribute to be set.
- value: the value to be assigned to the attribute.
Here is an example of using setattr():
class MyClass:
pass
my_obj = MyClass()
setattr(my_obj, 'my_attribute', 42)
print(my_obj.my_attribute) # output: 42
In the above example, we create an instance of the MyClass class and then use the setattr() function to set the value of its attribute named 'my_attribute' to 42. We then print the value of the attribute using the dot notation.
Note that you can also set attributes of built-in types such as lists, dictionaries, and strings using the setattr() function. However, it is more commonly used to set attributes of custom classes.