Tutorial Study Image

Python getattr()

The built-in function getattr() is used to get the value of a specified object’s attribute. In the case of a missing attribute, it returns the default value.


getattr(object, name[, default]) #Where object,name shows object name and attribute name respectively.

Syntax also like


object.name
 

getattr() Parameters:

In the case of the parameter we can directly input the attribute name in the program from the console. we can also set some default values, in case of attribute missing which enables us to complete some incomplete data.

Parameter Description Required / Optional
object  object whose named attribute's value is to be returned Required
name a string that contains the attribute's name Required
default the value that is returned when the named attribute is not found Optional

getattr() Return Value

The default value option of getattr() function helps to access any attribute which does not belong to the object.

Input Return Value
Attribute value of the named attribute of the given object
No attribute default value
 if an attribute is not found and no default  AttributeError exception

Examples of getattr() method in Python

Example 1:How getattr() works in Python?


class Person:
    age = 30
    name = "James"
pers = Person()
print('The age is:', getattr(pers, "age"))
print('The age is:', pers.age)
 

Output:

The age is: 30
The age is: 30

Example 2:getattr() when named attribute is not found


class Person:
    age = 30
    name = "James"
pers = Person()

# when default value is provided
print('The sex is:', getattr(pers, 'sex', 'Male'))

# when no default value is provided
print('The sex is:', getattr(pers, 'sex'))
 

Output:

The sex is: Male
AttributeError: 'Person' object has no attribute 'sex'

Example 3:getattr() raising attribute error


class GfG :
    name = "GeeksforGeeks"
    age = 24
  
# initializing object
obj = GfG()
  
# use of getattr
print("The name is " + getattr(obj,'name'))
  
# use of getattr with default
print("Description is " + getattr(obj, 'description' , 'CS Portal'))
  
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))
 

Output:

The name is GeeksforGeeks
Description is CS Portal

AttributeError: GfG instance has no attribute 'motto'