Python getattr()

Python getattr() builtin function is used to get the value of the named attribute of object.

In this tutorial, we will learn about the syntax of Python getattr() function, and learn how to use this function with the help of examples.

Syntax

The syntax of getattr() function is

getattr(object, name[, default])

where

ParameterRequired/OptionalDescription
objectRequiredA Python object.
nameRequiredA string. Name of the attribute in given object.
defaultOptionalDefault value if the attribute is not present.

Example

In this example, we take a class A, and get the value of attribute name in this class object using getattr() function.

Python Program

class A:
    name = 'Apple'
    age = 25

result = getattr(A, 'name')
print(result)
Try Online

Output

Apple

Conclusion

In this Python Tutorial, we have learnt the syntax of Python getattr() builtin function, and also learned how to use this function, with the help of Python example programs.