Join our newsletter for the latest updates.

Python hasattr()

The hasattr() method returns true if an object has the given named attribute and false if it does not.

The syntax of hasattr() method is:

hasattr(object, name)

hasattr() is called by getattr() to check to see if AttributeError is to be raised or not.

hasattr() Parameters

hasattr() method takes two parameters:

  • object - object whose named attribute is to be checked
  • name - name of the attribute to be searched

Return value from hasattr()

hasattr() method returns:

  • True, if object has the given named attribute
  • False, if object has no given named attribute

Example: How hasattr() works in Python?

class Person:
    age = 23
    name = 'Adam'

person = Person()

print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))


Person has age?: True
Person has salary?: False