Skip to main content

getattr()

The getattr() function in Python is a built-in function that is used to get the value of a specified attribute from an object. It takes two arguments - the object from which to retrieve the attribute, and the name of the attribute as a string. If the attribute is found, its value is returned; otherwise, an optional default value can be returned if specified.

Parameter Values

Parameter Description
object

The object whose attribute is to be accessed.

name

A string representing the name of the attribute to retrieve.

default

A default value to return if the attribute does not exist. If not provided, an AttributeError is raised.

Return Values

The getattr() function can return any type of object, as attributes can be of any type.

How to Use getattr() in Python

Example 1:

The getattr() function returns the value of a specified attribute from an object. If the attribute does not exist, it returns a default value or raises an AttributeError.

class Person:
    age = 25
    name = 'John'
p = Person()

print(getattr(p, 'age')) # Output: 25
print(getattr(p, 'gender', 'Male')) # Output: 'Male'
print(getattr(p, 'address')) # Raises AttributeError