The built-in function setattr() is used to assign the given value to the specified attribute of the specified object.
setattr(object, name, value) #where object indicates whose attribute value is needs to be change
Takes three parameters. We can say that setattr() is equivalent to object.attribute = value.
Parameter | Description | Required / Optional |
---|---|---|
object | an object whose attribute has to be set | Required |
name | attribute name | Required |
value | the value is given to the attribute | Required |
The setattr() method doesn't return anything it only assign objects attribute value. This function is useful in dynamic programming in such a situation we cannot assign attribute value using the 'dot' operator.
class PersonName:
name = 'Dany'
p = PersonName()
print('Before modification:', p.name)
# setting name to 'John'
setattr(p, 'name', 'John')
print('After modification:', p.name)
Output:
Before modification: Dany After modification: John
class PersonName:
name = 'Dany'
p = PersonName()
# setting attribute name to John
setattr(p, 'name', 'John')
print('Name is:', p.name)
# setting an attribute not present in Person
setattr(p, 'age', 23)
print('Age is:', p.age)
Output:
Name is: John Age is: 23
class PersonName:
def __init__(self):
self._name = None
def get_name(self):
print('get_name called')
return self._name
# for read-only attribute
name = property(get_name, None)
p = PersonName()
setattr(p, 'name', 'Sayooj')
Output:
Traceback (most recent call last): File "/Users/sayooj/Documents/github/journaldev/Python-3/basic_examples/python_setattr_example.py", line 39, insetattr(p, 'name', 'Sayooj') AttributeError: can't set attribute