89DEVs

Python: getattr() function

getattr() overview

The getattr() function returns the value of the given attribute of an object. If the attribute is not found, it returns the default value. If no default value is provided, an AttributeError exception is raised.

getattr() for existing attributes

If the attribute exists in the object, it is returned by the getattr() function. # getattr() for exisiting attributes class Dog: age = 4 name = "Mike" myDog = Dog() print('The age of ', getattr(myDog, "name"), ' is ', getattr(myDog, "age")) The attributes are returned and printed. The age of Mike is 4

getattr() with default value

If the attribute does not exists in the object and a default value is provided in the getattr() function, the default value is returned. # getattr() with default values class Dog: age = 4 name = "Mike" myDog = Dog() print('The age of ', getattr(myDog, "name"), ' is ', getattr(myDog, "age"), ' and the breed is ', getattr(myDog, "breed", "husky")) The breed attribute is not existent, the default value is returned and printed. The age of Mike is 4 and the breed is husky

getattr() when attribute does not exist

If the attribute does not exists and a default value is not defined, a AttributeError exception is raised. # getattr() when attribute does not exist and default value is not set class Dog: name = "Mike" myDog = Dog() print('The age of ', getattr(myDog, "name"), ' is ', getattr(myDog, "age")) The attribute age is missing and a default value is not set, a AttributeError exception is raised. AttributeError: 'Dog' object has no attribute 'age'

getattr() syntax

The syntax of the getattr() function is: getattr(object, attribute_name[, default_value])

getattr() arguments

The getattr() function accepts two or three arguments. The first two arguments are required, while the third argument is optional.
  • required: object, the object to be checked
  • required: attribute_name, the name of the attribute as string
  • optional: default_value, the default_value to be returned if the attribute is not found

getattr() return value

The getattr() function returns the attribute value if the attribute is found. If the attribute is not found, it returns the default value. If the default value is not specified a AttributeError exception is raised.

related functions

The related functions of the getattr() function are the hasattr() function to check if an attribute exists and the delattr() function to delete an existing attribute. The dir() function can be used to list all valid attributes of an given object.

                
        

Summary


Click to jump to section