getattr()

Published May 25, 2023
Contribute to Docs

The built-in getattr() function returns the value of the named property in a specified object/Class.

Syntax

getattr(object, name, default)

The getattr() method takes at least 2 parameters:

  • object, the given object
  • name, a string with the name of the attribute
  • default, (optional) a value to be returned when the named attribute does not exist

Examples

Example 1

class Cat:
hobby = 'sleeping'
age = 2
pet = Cat()
attr = getattr(pet, 'age')
print("My cat is", attr, "years old.")

This code will return:

My cat is 2 years old.

Example 2

class Cat:
hobby = 'sleeping'
age = 2
pet = Cat()
attr = getattr(pet, 'love')
print("My cat's favourite food is", attr)

This code will output an error, this because the Cat object does not have an attribute named love, and we did not set default parameter:

Traceback (most recent call last):
File "main.py", line 6, in <module>
attr = getattr(pet, 'love')
AttributeError: 'Cat' object has no attribute 'love'

Example 3

class Cat:
hobby = 'sleeping'
age = 2
pet = Cat()
attr = getattr(pet, 'love', 'tuna')
print("My cat's favourite food is", attr)

This code will return:

My cat's favourite food is tuna

Codebyte Example

Use getattr() to get the value of the named property in a specified object/class:

Code
Output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy