The setattr() function in Python is a built-in function that sets the attribute of a given object. It takes three arguments: the object, the attribute name as a string, and the attribute value. This function is commonly used to dynamically set attributes on objects at runtime.
Parameter Values
| Parameter | Description |
|---|---|
| object | The object whose attribute will be set. |
| name | A |
| value | The value to set the attribute to. |
Return Values
The setattr() function always returns None.
How to Use setattr() in Python
Example 1:
The setattr() function sets the value of the specified attribute of the specified object.
class Person:
name = 'John'
p = Person()
setattr(p, 'name', 'Alice')
print(p.name) # Output: Alice
Example 2:
The setattr() function can also be used to create new attributes if the specified attribute does not already exist.
class Person:
pass
p = Person()
setattr(p, 'age', 25)
print(p.age) # Output: 25