getattr()

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

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


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer