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)
print(getattr(tiger,'age')) # 5
print(getattr(tiger,'species')) # carnivores
print(hasattr(tiger,'age')) # True
In above code we collected the value of age attribute of tiger object.
Returning default value
Let us try to collect the value of one unknown attribute height by using the object.
print(tiger.height)
This line will generate error saying . AttributeError: 'Animal' object has no attribute 'height'
We can return default value of getattr() when the attribute is not found.
print(getattr(tiger,'height',' No such attribute '))