The hasattr()
function in Python checks whether an object has a specified attribute or not.
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 attribute attr
.attr
: The attribute we check for in the object obj
.The hasattr()
function returns a Boolean such that:
True
if the object obj
has the attribute attr
.False
if the object obj
does not have the attribute attr
.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))
Class1
, is declared in lines 1-4. obj1
is an instance declared of Class1
.hasattr()
function is used in line 8 to check if obj1
has the attribute attr2
. The hasattr()
function returns True
.delattr()
function is used in line 11 to delete the attribute attr2
of obj1
.hasattr()
function is used in line 13 to check if obj1
has the attribute attr2
. The hasattr()
function this time returns False
. This is because we deleted attr2
from obj1
using the delattr()
function.