Python getattr() Function Tutorial

Python provides the getattr() function which is used to get and return specified object attributes. Every attribute has a different name and this name is used to return the attribute value. If the specified attribute does not exist an error or default value provided to the getattr() function is returned.

getattr() Function Syntax

The syntax of the getattr() function is like below.

getattr(OBJECT,ATTRIBUTE_NAME,DEFAULT)
  • OBJECT is the object which provides the ATTRIBUTE.
  • ATTRIBUTE is stored in OBJECT.
  • DEFAULT is used if the specified attribute does not exist. This parameter is optional.

Get Attribute with getattr()

In the following example, we will create a class named Human. This class has two attributes named name and age . Then we will create an object by using the Human class and get these object attributes with the getattr() function.

class Human:
   name="ismail"
   age=38

person = Human()

name = getattr(person,'name')

age = getattr(person,'age')

“Attribute Is Not Found” Error

If the specified attribute does not exist in the specified object the Attribute is not found error is thrown. In the following example, we try to get surname attribute that does not exist.

class Human:
   name="ismail"
   age=38

person = Human()

surname = getattr(person,'surname')
“Attribute Is Not Found” Error

Default Value If Attribute Does Not Exist

getattr() returns existing attribute values but if the attribute does not exist an error is thrown which is described above. We can use the default value if the specified attribute does not exist instead of producing an error. The default value is provided to the getattr() function as the third parameter. In the following example, we check the attribute named surname , and if not exist the adamson value is returned by default.

class Human:
   name="ismail"
   age=38

person = Human()

surname = getattr(person,'surname','adamson')

Leave a Comment