setattr(object, attribute,value) adds or updates the value of attribute of the input object object (required ) , input object for which the attribute will be updated or added. attribute ( required ), attribute to be updated / added. value ( required ), new value of the attribute.
class Animal():
#class attributes
species='carnivores'
#instance attributes
def __init__(self1,name1,age):
self1.name= name1
self1.age=age
#instantiate the Animal class
tiger=Animal("Ronald",5) # object created
setattr(tiger,'height',3.5) # new attribute added
print(tiger.height) # showing value of new attribute
Output
3.5
In above code we created an object tiger. By using setattr() we added one more attibute height. The last line will print the value of new attribute.
Updating value of the attribute
We will change the value of one attribute.
class Animal():
#class attributes
species='carnivores'
#instance attributes
def __init__(self1,name1,age):
self1.name= name1
self1.age=age
#instantiate the Animal class
tiger=Animal("Ronald",5)
setattr(tiger,'age',6)
print("New age : ",tiger.age)
Output
New age : 6
Setting the value to None
tiger=Animal("Ronald",5)
setattr(tiger,'age',None)
print("New age : ",tiger.age)