The setattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.
Syntax
setattr(object, name, value)setattr() Parameters
Python setattr() function parameters:
| Parameter | Condition | Description |
|---|---|---|
object |
Required | Object whose attribute has to be set |
name |
Required | String that contains the attribute's name |
value |
Required | Value given to the attribute |
setattr() Return Value
Python setattr() function returns None.
Examples
Example 1: Basic usage of setattr() function to add a new Attribute
For example, consider the Person class defined with an attribute name. Create an instance p of Person and then use setattr() to add a new attribute age with value 25.
class Person:
def __init__(self, name):
self.name = name
p = Person('Tom')
setattr(p, 'age', 25)
print(p.name) # Output: Tom
print(p.age) # Output: 25output
Tom
25Example 2: Modifying an Existing Attribute
setattr() function can be used to modify an existing attribute of an object.
In the following example, the Person instance p has a name attribute set to 'Tom'. setattr() function is then used to change the name attribute to 'Ryan'.
The output shows that the name attribute has been successfully modified.
class Person:
name = 'Tom'
p = Person()
print('Before modification:', p.name)
setattr(p, 'name', 'Ryan')
print('After modification:', p.name) # Output: Ryanoutput
Before modification: Tom
After modification: Ryan