How to use setattr() in Python
setattr() in Python is a method that assigns a value to the attribute of an object.
Apart from assigning a value, it also has the following properties.
- It can be used to assign
Noneto an object attribute. - It can be used to initialize a new object attribute.
Syntax
setattr(obj, var, val)
Parameters
setattr() has the following parameters.
obj: object whose attribute has to be set.var: name of the attribute to be set.val: value given to the attribute.
Return value
setattr() returns None.
Example code 1: Simple
# creating a classclass sampleClass:number = "5"# creating an object of that classobj = sampleClass()# Before modificationprint("Before modification:", obj.number)# using setattr() to assign a new valuesetattr(obj, "number", "10")# After modificationprint("After modification:", obj.number)
Example code 2: Properties of setattr()
# creating a classclass sampleClass:number = "5"# creating an object of that classobj = sampleClass()# Before modificationprint("Before modifying 'number':", obj.number)# using setattr() to assign None to existing attributesetattr(obj, "number", None)# using setattr() to create a new attributesetattr(obj, "name", "Edpresso")# After modificationprint("After modifying 'number':", obj.number)print("After creating 'name':", obj.name)