Python | getattr() method
Last Updated :
25 Nov, 2024
The getattr() method in Python returns the value of a named attribute of an object. If the attribute is not found then it returns the default value provided. If no default is given and the attribute does not exist then it raises an AttributeError.
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.
Python
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().
Python
class GfG:
name = "GeeksforGeeks"
age = 24
obj = GfG()
print("The name is " + getattr(obj, 'name'))
Output:
The name is GeeksforGeeks
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.
Python
# 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'
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.
Python
# 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
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.
Python
# 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
Similar Reads
Python hasattr() method Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python. Syntax of hasattr() function Syntax : hasattr(obj, ke
2 min read
Instance method in Python A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Python Dictionary get() Method Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).Python Dictionary get() Method Syntax:Syntax : Dict.get(key, Value)Parameters: key: The key name of the item you want to return
3 min read
Python delattr() Function In Python, the delattr() function is used to delete an attribute from an object. In this article, we will learn about the Python delattr() function. Python delattr() Syntaxdelattr (object, name) Parameters: Object: An object from which we want to delete the attribute name: The name of the attribute
3 min read
Getopt module in Python The getopt module is a parser for command-line options based on the convention established by the Unix getopt() function. It is generally used for parsing an argument sequence, such as sys.argv.This module helps scripts parse command-line arguments in sys.argv. It works similarly to the C getopt() f
2 min read