Python hasattr() Method

The hasattr() method checks if an object of the class has the specified attribute.

Syntax:

hasattr(object, name)

Parameters:

  1. object: Required. The object whose attribute is to be checked.
  2. name: Required. Name of the attribute.

Return type:

Returns True if an object has the specified attribute else returns False.

The following example checks whether the built-in class str contains specified attributes or not.

Example: hasattr()
print('str has title: ', hasattr(str, 'title'))
print('str has __len__: ', hasattr(str, '__len__'))
print('str has isupper method: ', hasattr(str, 'isupper'))
print('str has isstring method: ', hasattr(str, 'isstring'))
Output
str has title: True
str has len: True
str has isupper method: True
str has isstring method: False

The hasattr() method can also be used with the user-defined classes, as shown below.

Example: hasattr() with Class
class student:
    name = "John"
    age = "18"
    
print("student has name: ", hasattr(student,"name"))
print("student has age: ", hasattr(student,"age"))
print("student has address: ", hasattr(student,"address"))
Output
student has name: True
student has age: True
student has address: False
Want to check how much you know Python?