Python setattr() function
Python setattr() function
The setattr() function sets the value of the specified attribute of the specified object.
Syntax
setattr(object, name, value)
Parameter
object: This parameter represents any object.
name: This parameter represents the name of the attribute you want to set.
value: It signifies the value you want to give the specified attribute.
Return
none
Example 1
# Python program explaining # the setattr() function # initializing class class Set: str_val = 'Hello' # initializing the object obj = Set() print("Before setattr name : ", obj.str_val) setattr(obj, 'str_val', 'Hello World') print("After setattr name : ", obj.str_val)
Output
Before setattr name : Hello After setattr name : Hello World
Example 2
# Python program explaining # the setattr() function class Student: stdName = "Reema" stdAge = 21 University="MVN" print("Before setting the value age is: ",Student.stdAge) setattr(Student, 'stdAge', 40) # The age property will now have the value: 40 val = getattr(Student, 'stdAge') print("After setting value the age is: ",Student.stdAge)
Output
Before setting the value age is: 21 After setting value the age is: 40