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

</>
Copy
getattr(object, name[, default])

where

ParameterRequired/
Optional
Description
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

</>
Copy
class A:
    name = 'Apple'
    age = 25

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

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.