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
Return value from getattr()
getattr()
method returns:
- value of the named attribute of the given object
default
, if no named attribute is foundAttributeError
exception, if named attribute is not found anddefault
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.