getattr(object, name,[default]) Returns the value of the attribute of the input object
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
Read more on Class Object and Attributes
Reading the value of the attribute of the object.
class Animal():

     #class attributes

     #instance attributes
    def __init__(self1,name1,age): name1

 #instantiate the Animal  class

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.
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 '))
 No such attribute 

All Built in Functions in Python setattr() delattr() hasattr()

Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer