The Python function hasattr evaluates to true when an object possesses the specified named attribute. Conversely, it yields false if the attribute is not present.
Python hasattr Function Syntax
It has the following syntax:
hasattr(object, attribute)
Parameters
- object: It is an object whose named attribute is to be checked.
- attribute: It is the name of the attribute that you want to search.
Return
It will return true if the specified object possesses the attribute with the provided name. If the attribute does not exist, it will return false.
Python hasattr Function Example
The example presented below demonstrates how the hasattr function operates in Python.
class Employee:
age = 21
name = 'Phill'
employee = Employee()
print('Employee has age?:', hasattr(employee, 'age'))
print('Employee has salary?:', hasattr(employee, 'salary'))
Output:
Employee has age?: True
Employee has salary?: False
Explanation:
In the preceding example, we defined a class called Employee, and subsequently, we instantiated an object of the Employee class, referred to as employee. The expression hasattr(employee, 'age') evaluates to true since the employee object possesses an attribute named age. Conversely, hasattr(employee, 'salary') yields a false value because the employee object does not include an attribute named salary.