Skip to main content

Python getattr() Function

The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

Syntax

getattr(object, attribute, default)
note

The above syntax is equivalent to object.name.

getattr() Parameters

Python getattr() function parameters:

ParameterConditionDescription
objectRequiredObject whose named attribute's value is to be returned
attributeRequiredString that contains the attribute's name
defaultOptionalValue that is returned when the named attribute is not found

getattr() Return Value

Python getattr() function returns

  • value of the named attribute of the given object
  • default, if no named attribute is found
  • AttributeError exception, if named attribute is not found and default is not defined

Examples

Example 1: Basic usage of getattr() function

class Person:
age = 25
name = "Tom"

person = Person()
print('The age is:', getattr(person, "age"))
print('The name is:', getattr(person, "name"))

output

The age is: 25
The name is: Tom

Example 2: getattr() when named attribute is not found (with and without default value)

class Person:
age = 25
name = "Tom"

person = Person()

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

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

output

The sex is: Male
Traceback (most recent call last):
File "main.py", line 11, in <module>
print('The sex is:', getattr(person, 'sex'))
AttributeError: 'Person' object has no attribute 'sex'
note

The named attribute sex is not present in the class Person. So, when calling getattr() method with a default value Male, it returns Male.

But, if we do not provide any default value, when the named attribute sex is not found, it raises an AttributeError saying the object has no sex attribute.

Example 3: Using getattr() to Call Methods

class MyClass:
def __init__(self):
pass
def my_method(self):
print("Method ran")

object = MyClass()
getattr(object, 'my_method')() # Calls the method 'my_method'

output

Method ran

Example 4: Comparison of performance between getattr() and object.name

import time

class MyClass:
name = "TutorialReference"
age = 25

obj = MyClass()

# Use of getattr to print name
start_getattr = time.time()
print("The name is " + getattr(obj, 'name'))
print("Time to execute getattr " + str(time.time() - start_getattr))

# Use of conventional method to print name
start_obj = time.time()
print("The name is " + obj.name)
print("Time to execute conventional method " + str(time.time() - start_obj))

output

The name is TutorialReference
Time to execute getattr 9.298324584960938e-06
The name is TutorialReference
Time to execute conventional method 2.86102294921875e-06