Python getattr Function with Examples

The getattr function in Python retrieves the value associated with a specified attribute of an object. In cases where the attribute does not exist, it provides a default value instead.

Python getattr Function Syntax

It has the following syntax:

Example

getattr(object, attribute, default)

Parameters

  • object : An object whose named attribute value is to be returned.
  • attribute : Name of the attribute of which you want to get the value.
  • default (optional): It is the value to return if the named attribute does not found.
  • Return

It provides the value associated with a specified attribute of an object. In the event that the attribute is not present, it yields the designated default value.

Different Examples for Python getattr Function

In this section, we will explore multiple examples of the Python getattr function.

Python getattr Function Example 1

The example provided below demonstrates how the getattr function operates in Python.

Example

class Details:

    age = 22

    name = "Vicky"

details = Details()

print('The age is:', getattr(details, "age"))

print('The age is:', details.age)

Output:

Output

The age is: 22

The age is: 22

Clarification: In the preceding illustration, we define a class referred to as Details, which contains several variables such as age, name, and others. This class outputs the values associated with the named attributes of an instance.

Python getattr Function Example 2

The following example demonstrates how the getattr function operates when the specified attribute name cannot be located.

Example

class Details:

    age = 22

    name = "Vicky"

details = Details()

# when default value is provided

print('The gender is:', getattr(details, 'gender', 'Male'))

# when no default value is provided

print('The gender is:', getattr(details, 'gender'))

Output:

Output

The gender is: Male

AttributeError: 'Details' object has no attribute 'gender'

Input Required

This code uses input(). Please provide values below: