hasattr() - Check if object has specific attribute


Python - hasattr()

Python hasattr() built-in function is used to check if specific attribute exists for an object. The function returns True if the object has specified attribute, or False otherwise.

In this tutorial, you will learn the syntax and usage of hasattr() built-in function with examples.

Syntax

The syntax of hasattr() function is

hasattr(object, attribute)

where

ParameterMandatory/
Optional
Description
objectMandatoryA Python object.
attributeMandatoryattribute is a string value.

Examples

1. Check if object has specific attribute

In the following program, we define a class named Student. This class has three attributes: name, age, and country.

We create a new object of the class type Student with some some values, and then check if the Student object has the attribute 'age'.

Python Program

class Student:
    def __init__(self, name, age, country):
        self.name = name
        self.age = age
        self.country = country

student1 = Student('Mike', 12, 'Canada')

if hasattr(student1, 'age') :
    print('The object has specified attribute.')
else :
    print('The object does not have specified attribute.')

Output

The object has specified attribute.

2. Negative Scenario

In the following program, we check if the Student type object has the attribute named grades. Since our Student class has no such attribute, hasattr() must return False.

Python Program

class Student:
    def __init__(self, name, age, country):
        self.name = name
        self.age = age
        self.country = country

student1 = Student('Mike', 12, 'Canada')

if hasattr(student1, 'grades') :
    print('The object has specified attribute.')
else :
    print('The object does not have specified attribute.')

Output

The object does not have specified attribute.

Related Tutorials

  • Python setattr() This built-in function sets the value of an attribute of an object.
  • Python getattr() This built-in function gets the value of an attribute of an object.
  • Python delattr() This built-in function deletes the attribute from an object.

Summary

In this Built-in Functions tutorial, we learned the syntax of the hasattr() built-in function, and how to use this function to check if the object has a specific attribute.