In this tutorial, we will learn about the python hasattr() method and its all uses with examples.
What is Python hasattr() method?
The Python hasattr() method returns true if the given attribute is present in the objects, and if it doesn’t present, it will return false.
The syntax of hasatter() method is follow.
Python hasattr() method parameters.
The hasattr() method takes two parameters:
- object – object name in which attribute has to be checked.
- name – The name of the attribute to be checked if it exists.
Let’s check some examples of hasattr() in python.
Example 1: How to use the hasattr() python method?
The Output will be as follow:
As we can see, first, we have checked the age attribute which is present in the given object that is returning us True, then we are checking the bread attribute which is not present in the given object, then it is returning False.
We can also check if the specified string attribute is present or not in the given sentence. For this, we will use python’s built-in class str to identify it as a string.
Example 2: How to use hasattr() with a string in python?
The output will be as follow:
Here the hasattr() method is checking whether the given string is present in the object.
Rules of hasattr()
- It will return True if the given attribute is present in the object.
- It will return False if the given attribute is not present in the object.
hasattr() is the same as getattr(), but the getattr() method will raise Attribute Error if the given attribute is not present in the object.