Python hasattr()
function is used to check the presence of an attribute in a given object. It returns a Boolean value, either True or False based on the presence of the attribute in that object. If the attribute is present it returns True otherwise False.
Syntax of hasattr() Funtion
The syntax of the hasattr()
function is as follows:
hasattr(object, name)
hasattr() Parameters
The hasattr()
function accepts two parameters:
- object – It can be any object wherein we want to check the presence of the attribute
- name – The name of the attribute whose presence is to be checked in the object. This value has to be a string.
hasattr() Return Value
The hasattr()
function always returns a Boolean value based on the presence of the attribute in the given object. It returns:
- True – If the attribute is present in the object
- False – If the attribute does not exist in the object
Working of hasattr() Function
The theoretical part we have understood. Now, let’s understand how it actually works with the help of an example.
To understand the working of the hasattr()
function, we have to first create a class and some objects of it and then we will check if the given attribute exists. Refer to the example below:
Example:
class Student: name = 'John' age = 23 student = Student() print('Does student has name?: ', hasattr(student, 'name')) print('Does student has marks?: ', hasattr(student, 'marks'))
Output:
Does student has name?: True Does student has marks?: False
In the above example, the student object has the ‘name’ attribute. Therefore, hasattr(student, 'name')
returns True. While the ‘marks’ attribute does not exist, hence returns False.
Check if a named method exists using hasattr()
In the previous example, we learned how to check if a named attribute exists on an object. But now the question arises, can we check if a named method exists on an object using hasattr()
? The answer is yes.
The second parameter can be the name of any variable or method. The only constraint is that it should be a string. Refer to the example below.
Example:
class Student: name = 'John' age = 23 def printAge(self): print(self.name, ' age is ', self.age) student = Student() student.printAge() print('Does student has printAge()?: ', hasattr(student, 'printAge')) print('Does student has printName()?: ', hasattr(student, 'printName'))
Output:
John age is 23 Does student has printAge()?: True Does student has printName()?: False