Python getattr() function
Published February 16, 2022The 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
![]() |
Article Contributed By :
|
|
|
|
396 Views |