What is the hasattr() function in Python?
The hasattr() function in Python checks whether an object has a specified attribute or not.
Syntax
The hasattr() function can be declared as shown in the code snippet below.
hasattr(obj, attr)
obj: The object we want to check to see if it has the attributeattr.attr: The attribute we check for in the objectobj.
Return value
The hasattr() function returns a Boolean such that:
- The return value is
Trueif the objectobjhas the attributeattr. - The return value is
Falseif the objectobjdoes not have the attributeattr.
Example
Consider the code snippet below, which demonstrates the use of the hasattr() function.
class Class1:attr1 = "attribute1"attr2 = "attribute2"attr3 = "attribute3"obj1 = Class1result = hasattr(obj1, 'attr2')print('obj1 has attr2: ' + str(result))delattr(obj1, 'attr2')result = hasattr(obj1, 'attr2')print('obj1 has attr2: ' + str(result))
Explanation
- A class,
Class1, is declared in lines 1-4.obj1is an instance declared ofClass1. - The
hasattr()function is used in line 8 to check ifobj1has the attributeattr2. Thehasattr()function returnsTrue. - The
delattr()function is used in line 11 to delete the attributeattr2ofobj1. - The
hasattr()function is used in line 13 to check ifobj1has the attributeattr2. Thehasattr()function this time returnsFalse. This is because we deletedattr2fromobj1using thedelattr()function.