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 | set() method
- Python | next() method
- Python | os.dup() method
- Python | os.getlogin() method
- Python | sympy.ff() method
- Python | os.getpid() method
- Python PIL | eval() method
- Python | sympy.rf() method
- Python | os.setgroups() method
- Python | sympy RGS method
- Python | sympy.crt() method
- Python PIL | getbands() method
- Python | os.getenv() method
- Python | os.ftruncate() 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 firstname.lastname@example.org. 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.