getattr() function is used to access the attribute value of an object and also give an option of executing the default value in case of unavailability of the key. This has greater application to check for available keys in web development and many other phases of day-to-day programming.
Syntax : getattr(obj, key, def)
obj : The object whose attributes need to be processed.
key : The attribute of object
def : The default value that need to be printed in case attribute is not found.
Object value if value is available, default value in case attribute is not present
and returns AttributeError in case attribute is not present and default value is not
Code #1 : Demonstrating working of getattr()
The name is GeeksforGeeks Description is CS Portal
AttributeError: GfG instance has no attribute 'motto'
Code #2 : Performance Analysis
The name is GeeksforGeeks Time to execute getattr 5.0067901611328125e-06 The name is GeeksforGeeks Time to execute conventional method 1.1920928955078125e-06
Result : Conventional method takes less time than getattr(), but when default values have to be used in case of missing attributes, getattr() is a good choice.
Applications : The are many applications of getattr(), few of them already mentioned in cases of absence of attributes of objects, in web developments where some of form attributes are optional. Also useful in cases of Machine Learning feature collections in case some features sometimes go missing in data collection.
- class method vs static method in Python
- Python | next() method
- Python | set() method
- Get() method for dictionaries in Python
- Python | Tensorflow exp() method
- Python | hasattr() method
- Python | Tensorflow tan() method
- Python | bytes() method
- Python | PyTorch sin() method
- Python | iter() method
- Python | setattr() method
- Python | Tensorflow sin() method
- Python | Tensorflow log() method
- Python | os.chmod method
- Python | os.chflags() method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.