Python setattr()
The python setattr() functions set the specific value of the specified attribute of the object.
Python setattr()
The syntax of the setattr() function is :
1
setattr(object, name, value)
setattr() Parameters
The setattr() functions take three parameters as argument:
- object - the name of the object whose attribute has to set.
- name - The name of the attribute
- value - value to be assigned to the attribute.
Example 1: How to use setattr() function in python?
1
2
3
4
5
6
7
8
9
10
11
class Dog:
name = 'Coco'
dog = Dog()
print('Before modification:', dog.name)
# setting name to 'John'
setattr(dog, 'name', 'Rick')
print('After modification:', dog.name)
Output:
1
2
3
Before modification: Coco
After modification: Rick
Rules of setattr()
If you want to get the value of the specific attribute, we recommend getatt() function.
This post is licensed under CC BY 4.0 by the author.
.png)