Python | getattr() method

08 Oct, 2021
Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.
Syntax : getattr(obj, key, def)
Parameters : 
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.
Returns : 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 specified. 
Python3
# Python code to demonstrate# working of getattr() # declaring classclass GfG:    name = "GeeksforGeeks"    age = 24 # initializing object and# python getattr() function callobj = GfG() # use of getattrprint("The name is " + getattr(obj, 'name')) # use of getattr with defaultprint("Description is " + getattr(obj,                                  'description',                                  'CS Portal')) # use of getattr without defaultprint("Motto is " + getattr(obj, 'motto'))
Output: 
The name is GeeksforGeeks
Description is CS Portal
Exception: 
AttributeError: GfG instance has no attribute 'motto'
Python3
# Python code to demonstrate# working of getattr() # declaring classclass GfG:    name = "GeeksforGeeks"    age = 24  # initializing objectobj = GfG() # use of getattr without defaultprint("Gender is " + getattr(obj, 'gender'))
Output:
AttributeError: 'GfG' object has no attribute 'gender'
Python3
# Python code to demonstrate# performance analysis of getattr()import time # declaring classclass GfG:    name = "GeeksforGeeks"    age = 24 # initializing objectobj = GfG() # use of getattr to print namestart_getattr = time.time()print("The name is " + getattr(obj, 'name'))print("Time to execute getattr " + str(time.time() - start_getattr)) # use of conventional method to print namestart_obj = time.time()print("The name is " + obj.name)print("Time to execute conventional method " + str(time.time() - start_obj))
Output: 
The name is GeeksforGeeks
Time to execute getattr 5.0067901611328125e-06
The name is GeeksforGeeks
Time to execute conventional method 1.1920928955078125e-06
Python3
# Python code to demonstrate# working of getattr() # declaring classclass GfG:    name = "GeeksforGeeks"    age = 24 # initializing objectobj = GfG() # use of getattr without defaultprint("Motto is " + getattr(obj, 'motto'))
Output:
AttributeError: 'GfG' object has no attribute 'motto'
Python3
# Python code to demonstrate# working of getattr() # declaring classclass GfG:         def __init__(self, name, age):        self.name = name        self.age = age     def call(self, x):        print(f"{self.name} called with parameters '{x}'")        return # initializing objectobj = GfG("Vivek", 10)print(obj)print(GfG)print(getattr(obj,'call')) getattr(obj,'call')('arg')
Output:
<__main__.GfG object at 0x0000023C1ED92748>
<class '__main__.GfG'>
<bound method GfG.call of <__main__.GfG object at 0x0000023C1ED92748>>
Vivek called with parameters 'arg'
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(), a few of them already mentioned in cases of absence of attributes of objects, in web developments where some of the form attributes are optional. Also useful in cases of Machine Learning feature collections in case some features sometimes go missing in data collection.
kumar_satyam
sagartomar9927
Python-Built-in-functions
python-object
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.