![]() |
VOOZH | about |
Python setattr() method is used to assign the object attribute its value. The setattr() can also be used to initialize a new object attribute. Also, setattr() can be used to assign None to any object attribute.
Example :
Output :
name: kiran
Syntax : setattr(obj, var, val)
Parameters :
- obj : Object whose which attribute is to be assigned.
- var : object attribute which has to be assigned.
- val : value with which variable is to be assigned.
Returns : None
In the given example, we have defined a animal class with a class variable name and we are showing how can we set the value of the variable with setattr().
Output :
Before modification: lucky After modification: Woozoo
In this example, we have defined a Gfg class and we have set the name and descr variables to None after that we have set the variable with setattr() and printed it. After that, we created a variable named a value that was not found in the class with setattr() and printing it in Python.
Output :
Before using setattr: name: None descr: None After using setattr: name: GeeksForGeeks descr: CS Portal New attribute created, gfg.value: 5
Here we are creating attributes of the class 'Dict2Class' dynamically using setattr() function by passing a dictionary with some keys and values to the __init__() method of the class.
Output :
After Converting Dictionary to Class : Geeks 1223 Python <class '__main__.Dict2Class'>
Here we will create read-only attributes of the object using property() function in Python and if we try to set the attribute's value using setattr() function then an exception will rise.
Output :
---> 16 setattr(p, 'n', 'rajav') AttributeError: can't set attribute