Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

The getattr() Function in Python

Last updated by Dipen Dadhaniya on Sep 25, 2024 at 11:02 PM | Reading time: 5 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

The getattr() Function in Python
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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:

  • What Is the getattr() Function in Python and What Does It Do?
  • The getattr() Function in Python: Syntax
  • The getattr() Function in Python: Example
  • FAQs on the getattr() Function in Python

What Is the getattr() Function in Python and What Does It Do?

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.

The getattr() Function in Python: Syntax


getattr(object, key, defaultValue)

Parameters: 

  • object: The object whose attribute we need to process.
  • key: An attribute of the given object.
  • defaultValue: The default value we need to print in case the attribute is not found.

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.

The getattr() Function in Python: Example

Here, we take a look at how you can use the Python function getattr() next time you need it:

Code


# 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))

Output


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. 

FAQs on the getattr() Function in Python

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.

Ready to Nail Your Next Coding Interview?

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!

Sign up now!

Last updated on: 
October 10, 2024
Author

Dipen Dadhaniya

Engineering Manager at Interview Kickstart

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

The getattr() Function in Python

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image