Python getattr() Method

The getattr() method returns the value of the attribute of an object. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Syntax:

getattr(object, name, default)

Parameters:

  1. object: An object of the class whose attribute value needs to be returned.
  2. name: The string name of the attribute.
  3. default. (Optional) A value to be returned if the attribute is not found.

Return Value:

  • Returns value of the attribute of the given object.
  • Returns the specified default value if attribute not found.
  • If the default value not specified, then throws AttributeError.

The following example demonstrates the getattr() method.

Example: getattr()
class student:
    name = 'John'
    age = 18
    
std = student() # creating object

print('student name is ', getattr(std, 'name'))

std.name = 'Bill' # updating value
print('student name changed to ', getattr(std, 'name'))
Output
student name is John
student name changed to Bill

Above, getattr(std, 'name') returns the value of the name property of the std object, which is John. It always returns the latest value even after updating a property value.

If the attribute specified in the argument is not found, an AttributeError exception is thrown.

Example: getattr()
class student:
    name = 'John'
    age = '18'

std = student()
attr = getattr(std, 'subject')
Output
Traceback (most recent call last):
    attr = getattr(std, 'subject')
AttributeError: type object 'student' has no attribute 'subject'

The default parameter can be passed to avoid the above error, which returns the default value if the attribute is not found.

Example: getattr()
class student:
    name = 'John'
    age = '18'

std = student()
subject = getattr(std, 'subject', 'Not supported')
print("student's subject: ", subject)
Output
student's subject: Not supported

Instead of getattr() method, the . operator can also be used to access the attribute value if you are sure that an object has that attribute.

Example: getattr()
class student:
    name = 'John'
    age = '18'

std = student()
print('student name is ', std.name)
Output
student name is John

The following get's the method of the built-in list object.

Example: getattr()
nums= [1, 2, 3, 4, 5]
rev = getattr(nums, 'reverse')
rev()
print(nums)
Output
[5, 4, 3, 2, 1]