Python getattr() function

Published February 16, 2022

The Python getattr() method is used to obtain an object's attribute value and provides the option of executing the default value if the key is unavailable. This function works by returning the value of the specified attribute in an object. If the attribute is not found, the function provides the default value.


Syntax
The syntax of the getattr() function is as follows:

getattr(object, key, default value)


where:
Object: the specified object in which attributes will be processed
key:  the object attribute


default value: the returned value if the attribute is not found

Example
Consider the following example, in which the getattr() function fails to find the attribute.
 

class python:
            name = "I Love Python"
            words = 10
objecto = python()
print("Programming language is " + getattr(objecto, 'language'))

 

Output

Python getattr() function

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

396 Views