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.
- Difference between Method Overloading and Method Overriding in Python
- class method vs static method in Python
- Python | os.dup() method
- Python | next() method
- Python | set() method
- Python | os.writev() method
- Python | os.pwrite() method
- Python | os.getpgrp() method
- Python | os.readlink() method
- Python | os.scandir() method
- Python | os.getpgid() method
- Python | os.tcgetpgrp() method
- Python | after method in Tkinter
- Python | os.setregid() method
- Python | os.getsid() method
- Python | os.pipe() method
- Python | os.openpty() method
- Python | sys.getallocatedblocks() method
- Python PIL | blend() method
- Python | os.getgrouplist() method