The hasattr() method returns True if a specified object has the specified attribute, otherwise False.
Python hasattr() is an inbuilt utility function that returns True if the object has the given named attribute; otherwise, it returns False. See the following syntax.
Object: Whose named attribute is to be checked.
Name: Refers to the name of the attribute to be searched.
The hasattr() function returns two types of value:
True: If the object has the given named attribute.
False: If the object does not have the given named attribute.
# Declaring the class class Student: name = "Debasis" age = 20 sex = "Male" # Initializing object of Student class std = Student() # Checking if the name attribute is present or not # This will return true print("Does class contains sex ?", hasattr(std, 'sex')) # This will return false print("Does class has height ?", hasattr(std, 'height'))
See the output.
Does class contains sex? True Does class has height? False
The function can be used to check keys to avoid unnecessary errors in case of accessing missing keys. Chaining of hasattr() is used sometimes to prevent the entry of one associated attribute if the other is not present.
Python hasattr() function vs in
The benefit of the hasattr() function is visible when the attribute value is determined dynamically, such as getting it from user input. We can’t do the same thing with k in obj because of dynamic nature.
Let’s look at another instance where we will ask the user to enter the attribute value, and then use hasattr() to check if it exists or not and proceed accordingly.
See the following code.
# app.py class Netflix: season = 0 name = '' def __init__(self, i, n): self.season = i self.name = n series = Netflix(3, 'StangerThings') data = input('\nPlease enter Netflix attribute to get details:\n') if hasattr(series, data): print(data, '=', getattr(series, data)) else: print('invalid netflix attribute')
See the output.
➜ pyt python3 app.py Please enter Netflix attribute to get details: name name = StangerThings ➜ pyt python3 app.py Please enter Netflix attribute to get details: season season = 3 ➜ pyt
Python hasattr() is the utility function to check if an attribute is present or not for the object before we try to use it in our program.
We can quickly implement the function or use the try-expect to have this logic in our program, but using this function is recommended to have the clean code.