Interview Kickstart has enabled over 21000 engineers to uplevel.
Python supports object-oriented programming and has a concise, readable, and easy-to-learn syntax. It is no wonder that it is one of the most popular programming languages. An integral part of Python are its built-in functions.
We've written a series of articles to help you learn and brush up on the most useful Python functions. In this article, we’ll learn about Python's getattr() function and how to use it.
If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Python Exit commands, and Type and Isinstance In Python for more content on Python coding interview preparation.
Having trained over 10,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!
At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.
Want to nail your next tech interview? Sign up for our FREE Webinar.
In this article, we’ll cover:
Python getattr() function is a built-in function used to access the attribute value of an object. It is also used to execute the default value in case the attribute/key does not exist. The conventional method of accessing the attribute value generally takes less time than getattr(). But if we need to use default values in case of missing attributes, getattr() is appropriate.
The Python function getattr() is used in web developments involving optional form attributes. Additionally, it is also used in Machine Learning feature collection cases, where features go missing at times in data collection.
getattr(object, key, defaultValue)
Parameters:
Return Value:
Python’s getattr() function returns the object value if the value (attribute) exists or the default value if the attribute doesn’t exist.
If neither the attribute is present nor the default value specified, getattr() throws an AttributeError in Python.
Here, we take a look at how you can use the Python function getattr() next time you need it:
# Using getattr() in Python
# For the performance analysis of getattr() done later in the example
import time
# Creating a class to use in the example
class fruit:
name = "Apple"
color = "Red"
weightInGrams = "100"
# Initializing an object of the class fruit
objectFruit1 = fruit()
# Using getattr() to print attribute values
print("The name of the fruit is " + getattr(objectFruit1, 'name'))
print("The color of the fruit is " + getattr(objectFruit1, 'color'))
# Using getattr() giving default value to be used if attribute value does not exist
print("The weightInGrams of the fruit is " + getattr(objectFruit1, 'weightInGrams', "not mentioned"))
print("The taste of the fruit is " + getattr(objectFruit1, 'taste', "not described"))
# Performance analysis of getattr()
getattrBeginTime = time.time()
print(getattr(objectFruit1, 'name'))
print("Time taken to execute getattr() = " + str(time.time() - getattrBeginTime))
# Contrasting the above with the performance of conventional method to get the attribute value
getattrBeginTime2 = time.time()
print(objectFruit1.name)
print("Time to execute conventional method " + str(time.time() - getattrBeginTime2))
The name of the fruit is Apple
The color of the fruit is Red
The weightInGrams of the fruit is 100
The taste of the fruit is not described
Apple
Time taken to execute getattr() = 9.5367431640625e-07
Apple
Time to execute conventional method 4.76837158203125e-07
Found this article helpful? You can learn about more Python functions in our learn folder.
Q1. What does the getattr() function do in Python?
In Python, the function getattr() takes an object, an attribute of an object, and returns the value of that attribute if it exists. If the attribute value does not exist, a specified default value is returned.
Q2. What’s the behavior of getattr() in Python in case attribute value does not exist and default value is not specified either?
AttributeError is thrown if, in the absence of attribute value, getattr() has not received a default value as a parameter to use in such cases.
Q3. Why do we use getattr() in Python?
A significant reason to use getattr() in Python is you can manually get the attribute name as input from your console and use the attribute name as a string in getattr directly to get the value. And in case of an absent attribute, you can specify a default value, helping us fill in some of the blanks in our data.
Q4. Should you use getattr() in Python?
If you need to return a default value for absent values, that’s the main use case of getattr(). Otherwise, the conventional, direct value accessing method can be faster.
Q5. Is getattr() slow Python?
Yes, compared to the direct conventional method of accessing an attribute of a given object, the performance of getattr() is slower.
Whether you’re a coding engineer gunning for a software developer or software engineer role, a tech lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!
If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!
Attend our webinar on
"How to nail your next tech interview" and learn