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(hasattr(tiger,'age')) # True
print(hasattr(tiger,'height')) # False
In above code we got True for the attribute age , but got False for attribute height as it is not declared.
Benefits of Using hasattr()
Safe Attribute Access: It allows for safe attribute access by checking for an attribute's existence before accessing it, thus avoiding potential AttributeErrors.
Dynamic Code: Useful in scenarios where we need to work with objects dynamically, and we might not know if an object has a specific attribute.
Conditional Logic: Enables writing conditional logic based on the presence or absence of attributes in objects, making our code more flexible and robust.