Function Details: getattr
Description
Gets a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
Extended Description
The getattr() function is used to get the value of a named attribute of an object. It is useful when you need to access attributes dynamically or when you're not sure if an attribute exists. If the named attribute does not exist, getattr() will raise an AttributeError, unless a default value is provided as the third argument.
Exceptions
- AttributeError: If the named attribute does not exist and no default value is specified
Read More about getattr from Python Documentation
Function Signature
getattr(object: Any, name: str, default: Optional[Any] = None) -> Any
Module: builtins
Parameters
object: The object from which to get the attribute. name: A string containing the name of the attribute to get. default: An optional default value to return if the attribute does not exist.
Parameter List
- object: Any
- name: str
- default: Optional[Any]
Return
Returns the value of the named attribute of the object. If the attribute doesn't exist and a default is provided, returns the default value.
Return Type
Any
Output
Explanation
This example shows basic usage of getattr() to access existing attributes and provide a default for a non-existent attribute.