What does hasattr() function do in Python?

The hasattr() method in Python

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)

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

The hasattr() method takes two parameters −

The hasattr() method returns −

True, if object has the given named attribute

False, if object has no given named attribute


class Male:
    age = 21
    name = 'x'
x = Male()
print('Male has age?:', hasattr(x, 'age'))
print('Male has salary?:', hasattr(x, 'salary'))


This gives the output

('Male has age?:', True)
('Male has salary?:', False)