Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython | getattr() method

Python | getattr() method

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.

Python getattr() Method Syntax

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.

Example

In the given example, getattr() is used to access both attributes and methods of an object dynamically. It provides flexibility in working with objects whose attributes or methods are not known in advance.

Python3




class Calculator:
    def add(self, a, b):
        return a + b
 
calc = Calculator()
 
# Accessing a method dynamically
operation = getattr(calc, "add")
result = operation(3, 5)
print(result)


Output :

8

How getattr() works in Python?

The getattr() function in Python is a built-in function that allows you to dynamically access an object’s attributes or methods by name. To understand how getattr() works in Python, we have created a class named GFG with two class attributes name, and age. Further, we are creating two attribute names and ages. Then we created an object of the class and we are getting the attribute name-value with getattr().

Python3




class GfG:
    name = "Lazyroar"
    age = 24
obj = GfG()
 
print("The name is " + getattr(obj, 'name'))


Output:

The name is Lazyroar

getattr() in Python Examples

getattr() when the Named Attribute is not Found

In this example, we have defined a class name GFG and there are two class variables named, the age we call the gender attribute which is not present in the class, which is showing the output AttributeError.

Python3




# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "Lazyroar"
    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'

Performance Analysis and getattr Python with Parameter

In this example, we are using the time class to show that getattr() takes more time rather than the conventional method in Python.

Python3




# Python code to demonstrate
# performance analysis of getattr()
import time
 
# declaring class
class GfG:
    name = "Lazyroar"
    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 Lazyroar
Time to execute getattr 5.0067901611328125e-06
The name is Lazyroar
Time to execute conventional method 1.1920928955078125e-06

Python getattr() function Call

In this example, we have created a GFG class and a call function. We have created an object of GFG class and we have called the getarr() in Python with the object, function, and parameter.

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'

Applications of getattr() in Python

The getattr() function in Python is commonly used in various applications and scenarios. Such as:

  • Accessing attributes dynamically
  • Handling optional attributes
  • Configuring objects
  • API integration
RELATED ARTICLES

Most Popular

Recent Comments