How to check for attributes in Python

Overview

In Python, the hasattr() function checks if a given object has a specified attribute.

Syntax

hasattr(object, name)

Parameters

  • object: This represents the specified object that needs to be checked.

  • attribute: This is the name of the attribute to be searched.

Return type

The hasattr() function returns True if a given object has the specified attribute. Otherwise, it returns False.

Code

The following code shows how to use the hasattr() function in Python:

# Create the Animal class
class Animal:
name = 'Dog'
color = 'brown'
breed = 'Dachsador'
# Create an instance of the Animal class
animal = Animal()
print('Does Animal has name?:', hasattr(animal, 'name'))
print('Does it has an age?:', hasattr(animal, 'age'))
print('Does it has a breed?:', hasattr(animal, 'breed'))

Explanation

  • Lines 2–5: We create a class named Animal which has the attributes name, color, and breed.

  • Line 7: We create an instance of the Animal class to access its attributes.

  • Lines 9–11: We use the hasattr() function to check if the given object has the specified attribute. Finally, we display the result.

Free Resources