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.
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
tiger=Animal("Ronald",5)
setattr(tiger,'age',None)
print("New age : ",tiger.age)
Output
New age : None
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.