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.
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
Given below is the syntax of the
attributeExistsOrNot = hasattr(object, name)
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
hasttar() returns a boolean value.
True if there exists a given named attribute for the given object class and otherwise
Example: Usage of the
The following example illustrates the usage of the Python built-in
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'))
Is there the attribute 'Physics' for Marks class obj? True
Is there the attribute 'ComputerScience' for Marks class obj? False
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!