Python hasattr() Function

Python Built In Hasattr() Function

This is a detailed tutorial of the Python built-in hasattr() Function. Learn to check if a given python class object has a given named attribute or not.

Python hasattr() Function

As the name of the function suggested it checks if a given Python class object has an attribute for the given name or not. It returns a boolean value accordingly, i.e. True if the attribute of the given name exists for the given class object and False if it’s not.

Note. Even the getattr() function also calls the hasattr() function to first check if the given attribute exists or not. As if the attribute would not exist, the hasattr() function will return False and checking this False condition, the getattr() method is able to raise the AttributeError.

Syntax

Given below is the syntax of the hasattr() function.

hasattr() Parameters

This function takes two different arguments as described below.

  • object. This is the object for which you want to check the class attribute existence.
  • name. This is the name of the attribute as a string that you want to check for the object passed in the first argument.

hasattr() Return Value

The function hasttar() returns a boolean value.

It returns True if there exists a given named attribute for the given object class and otherwise False.

Example: Usage of the hasattr() Function

The following example illustrates the usage of the Python built-in hasattr() function.

class Marks:
    English = 99
    Physics = 95
    Chemistry = 97
    Mathematics = 100
    
obj = Marks()
#Checking if the attribute Physics exists for the class object or not
print("Is there the attribute 'Physics' for Marks class obj?", hasattr(obj,'Physics'))

#Checking if the attribute ComputerScience exists for the class object or not
print("Is there the attribute 'ComputerScience' for Marks class obj?", hasattr(obj,'ComputerScience'))

Output.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *