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
- Python | PyTorch tan() method
- Python | hash() method
- Python | object() method
- Python | PyTorch cos() method
- Python | os.chflags() method
- Python | Tensorflow cos() method
- Python | range() method
- Python | setattr() method
- Python | iter() method
- Python | Tensorflow abs() method
- Python | os.chmod method
- Python | Tensorflow log() method