object | Object for which the attribute is required. |
name | name of the the attribute for which the value is required. |
default | (optional) Value to be returned if attribute is not found |
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.
print(tiger.height)
This line will generate error saying . AttributeError: 'Animal' object has no attribute 'height'
print(getattr(tiger,'height',' No such attribute '))
Output
No such attribute
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.