The getattr() function in Python is used to access the value of an attribute of the specified object. In case the specified attribute is not the property of the object, it returns the specified default value.

Syntax:

getattr(object, attribute, default)

Python getattr() Parameters

ParameterConditionDescription
objectRequiredThe object whose attribute’s values need to be returned
attributeRequiredThe name of the attribute in the form of a string
defaultOptionalDefault value to be returned if attribute not found

Return value

The getattr() function returns the value of an attribute if available otherwise returns the specified default value.

If the default value is not specified the interpreter will throw AttributeError error.

Python getattr() Examples

Example 1: Without default value

class PC:
  ram = 8
  cpu = 16
  disk = 255

#creating object
myPc = PC()

print("CPU: ",getattr(myPc, 'cpu'))
print("RAM: ",getattr(myPc, 'ram'))

#Not providing the default value
print("GRAPHICS: ",getattr(myPc, 'graphics'))

Output

CPU: 16
RAM: 8
AttributeError: ‘PC’ object has no attribute ‘graphics’>/samp>

Example 2: With the default value

class PC:
  ram = 8
  cpu = 16
  disk = 255

#creating object
myPc = PC()

print("CPU: ",getattr(myPc, 'cpu'))
print("RAM: ",getattr(myPc, 'ram'))

#providing the default
print("GRAPHICS: ",getattr(myPc, 'graphics', "NO_GRAPHICS_AVL"))

Output:

CPU: 16
RAM: 8
GRAPHICS: NO_GRAPHICS_AVL

The getattr() in python is useful when we are not sure whether a particular object has a specific attribute or not. In case the specified attribute doesn’t exist, we can supply the default value.

Leave a Reply