Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
attribute
communitycreator

What is the hasattr() function in Python?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
attribute
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring