Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python | getattr() method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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. 

How getattr() works in Python

Example 1: Demonstrating working of getattr() 

Python3




# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object and
# python getattr() function call
obj = GfG()
 
# use of getattr
print("The name is " + getattr(obj, 'name'))
 
# use of getattr with default
print("Description is " + getattr(obj,
                                  'description',
                                  'CS Portal'))
 
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))


Output: 

The name is GeeksforGeeks
Description is CS Portal

Exception: 

AttributeError: GfG instance has no attribute 'motto'

Example 2: getattr() when named attribute is not found

Python3




# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
 
# initializing object
obj = GfG()
 
# use of getattr without default
print("Gender is " + getattr(obj, 'gender'))


Output:

AttributeError: 'GfG' object has no attribute 'gender'

 Example 3: Performance Analysis and getattr python with parameter

Python3




# Python code to demonstrate
# performance analysis of getattr()
import time
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of getattr to print name
start_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 name
start_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

Example 4:  getattr Python default value

Python3




# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))


Output:

AttributeError: 'GfG' object has no attribute 'motto'

Example 5: Python getattr() function call

Python3




# Python code to demonstrate
# working of getattr()
 
# declaring class
class 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 object
obj = 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: There 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.


My Personal Notes arrow_drop_up
Last Updated : 15 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials