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
Parameter | Required/Optional | Description |
---|---|---|
object | Required | A Python object. |
name | Required | A string. Name of the attribute in given object. |
default | Optional | Default value if the attribute is not present. |
ADVERTISEMENT
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.