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 & 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.