The Wayback Machine - https://web.archive.org/web/20240810231316/https://www.geeksforgeeks.org/python-hasattr-method/
Open In App

Python hasattr() method

Last Updated : 05 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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, key)

Parameters : 

  • obj : The object whose which attribute has to be checked.
  • key : Attribute which needs to be checked.

Returns : Returns True, if attribute is present else returns False. 

Example 1:  Python hasattr() function example

Here we will check if an object has an attribute, to find attributes of the object in python we have demonstrated the following code.

Python3




# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
 
# initializing object
obj = GfG()
 
# using hasattr() to check name
print("Does name exist ? " + str(hasattr(obj, 'name')))
 
# using hasattr() to check motto
print("Does motto exist ? " + str(hasattr(obj, 'motto')))


Output: 

Does name exist ? True
Does motto exist ? False

Example 2: Performance analysis between hasattr() method and try statement

This is the Simple Ways to Check if an Object has Attribute in Python or not using performance analysis between hasattr() function and try statement.

Python3




import time
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of hasattr to check motto
start_hasattr = time.time()
if(hasattr(obj, 'motto')):
    print("Motto is there")
else:
    print("No Motto")
 
print("Time to execute hasattr : " + str(time.time() - start_hasattr))
 
# use of try/except to check motto
start_try = time.time()
try:
    print(obj.motto)
    print("Motto is there")
except AttributeError:
    print("No Motto")
print("Time to execute try : " + str(time.time() - start_try))


Output: 

No Motto
Time to execute hasattr : 5.245208740234375e-06
No Motto
Time to execute try : 2.6226043701171875e-06

Result: Conventional try/except takes lesser time than hasattr(), but for readability of code, hasattr() is always a better choice.

Applications: This function can be used to check keys to avoid unnecessary errors in case of accessing absent keys. Chaining of hasattr() is used sometimes to avoid entry of one associated attribute if the other is not present.



Similar Reads

Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
three90RightbarBannerImg