Python getattr() function is used to access the value of an attribute/property of an object if available, else we can supply some default value explicitly if that named attribute is not a property of the object.

Syntax:

Python getattr() Parameters

  • object – The object whose attribute’s values need to be returned.
  • attribute – The name of the attribute in the form of string.
  • default [optional] – Default value to be returned if attribute not found.

Return value of getattr():

getattr() function in python returns the value of an attribute if available otherwise returns the default value if specified otherwise will throw AttributeError if default value is not provided as the third parameter.

Python getattr() Examples

Example 1: Without default value

Output

Example 2: With default value

Output

getattr() in python is useful when we are not sure whether a particular object has a specific attribute or not. In case of NOT, we can supply or own default value.

Leave a Reply

Close Menu