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.
None
to an object attribute.setattr(obj, var, val)
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.setattr()
returns None
.
# 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)
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)