Python getattr()

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.

Example

class Student:
  marks = 88
  name = 'Sheeran'

person = Student()

name = getattr(person, 'name')
print(name)
marks = getattr(person, 'marks')
print(marks) # Output: Sheeran # 88

getattr() Syntax

The syntax of getattr() method is:

getattr(object, name[, default])

The above syntax is equivalent to:

object.name

getattr() Parameters

getattr() method takes multiple parameters:

  • object - object whose named attribute's value is to be returned
  • name - string that contains the attribute's name
  • default (Optional) - value that is returned when the named attribute is not found

getattr() Return Value

getattr() method 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

Example 1: How getattr() works in Python?

class Person:
    age = 23
    name = "Adam"

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

Output

The age is: 23
The age is: 23

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

class Person:
    age = 23
    name = "Adam"

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
AttributeError: 'Person' object has no attribute 'sex'

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 don't provide any default value, when the named attribute sex is not found, it raises an AttributeError saying the object has no sex attribute.

Did you find this article helpful?