In this article, you will learn all about setattr function in python to set the value of specified attribute of specified obeject.
In the previous tutorial, we have seen all about lots of Python built-in functions along with examples.
Headings of Contents
setattr() function in Python
Python setattr function is a Python built-in function that is used to set the value of a specified attribute from a specified object. setattr method gives another facility to assign a default value if the specified attribute does not exist.
Syntax:
The syntax of setattr function in python is:-
setattr(object, attribute, value)
Parameter:
setattr function in python support three parameters.
- object:- Required, An object.
- attribute:- The name of the attribute you want to value from.
- value:- Value to be return, If the specified attribute does not exist.
Return Value:
The return value of python setattr method is None.
Python setattr example
To understand python setattr function, we have created a simple class named Student.
Example:
class Student:
name = 'Vishvajit'
roll = 100
course = 'BCA'
occupation = 'Programmer'
#Use setattr function to set the value of occupation attribute.
result = getattr(Student, 'occupation')
print(result)
setattr(Student, 'occupation', 'Civi Engineer')
result = getattr(Student, 'occupation')
print(result)
Output
Programmer
Civil Engineer
What happens, If the specified attribute does not exist, let see.
Example:
class Student:
name = 'Vishvajit'
roll = 100
course = 'BCA'
occupation = 'Programmer'
#Use setattr function to set the value of the address attribute that does not exist.
setattr(Student, 'address', 'Civil Engineer')
result = getattr(Student, 'address')
print(result)
Output will be Civil Engineer
If you will execute the above program, A new attribute ‘address‘ will be created. To check, you can use the Python dir() function.
print(dir(Students))
Output
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'address', 'course', 'name', 'occupation', 'roll']
Conclusion
So In this article, you have learned python setattr function to set the value of specified attribute from specified object along with various example.
If this article really helpful for your, please share it with your friends who want to learn python built-in functions.
Python built-in functions
For more information:- Click Here