Python setattr() function

Published February 16, 2022

Among the typical activities in programming is assigning values to variables. You can achieve this by using object and constructor functions. The setattr() method offers an alternative way to assign values to variables.
Python's setattr() function is used to assign attributes to object values.

Syntax
 

setattr(object, var, value)

where:
object: the object to be assigned the attribute
var: the  attribute to be assigned  to the object
value: the value assigned  to the variable


Example

class ILP:
    my_var = 'ILovePython'
my_object = ILP()
print("Before setattr variable name : ", my_object.my_var)
setattr(my_object, 'my_var', 'ILovePython')
print("After setattr variable name : ", my_object.my_var)


Output

Before setattr variable name :  ILovePython
After setattr variable name :  ILovePython

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

225 Views