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 attribute attr.
  • attr: The attribute we check for in the object obj.

Return value

The hasattr() function returns a Boolean such that:

  • The return value is True if the object obj has the attribute attr.
  • The return value is False if the object obj does not have the attribute attr.

Example

Consider the code snippet below, which demonstrates the use of the hasattr() function.

class Class1:
attr1 = "attribute1"
attr2 = "attribute2"
attr3 = "attribute3"
obj1 = Class1
result = 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. obj1 is an instance declared of Class1.
  • The hasattr() function is used in line 8 to check if obj1 has the attribute attr2. The hasattr() function returns True.
  • The delattr() function is used in line 11 to delete the attribute attr2 of obj1.
  • The 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.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources