hasattr function in python

The built-in function hasattr() checks whether an attribute is part of an object. The function returns true if the attribute is present in an object. It returns false otherwise.

Built-in Functions Updated 29 Jun 2021 2 min read

Overview

  • A Python object has state, behaviour and identity. The state of the object is given by the values of its atributes. The behaviour through its functions and identity through its reference(s).
  • In strict terms or broader terms, the methods are also the properties of the objects.
    As Python honours this, hasattr() works for examining the presence of a method with a specific name on a given object.
  • An object can be examined for the presence of a specific attribute or a method through the hasattr() method.
  • The function hasattr() comes handy when the code involves duck typing. Duck typing assumes certain behaviour of an object through verifying the presence of certain members of an object. The member could be a method or attribute.

Example 1 - Check for the existence of an attribute on a Python object

python
# Example Python program that checks an object for an attribute

# A simple definition of a Planet class

            class Planet:

                def __init__(self, name, diameter, moonCount,

                             surfaceGravity, orbitalPeriod, supportsLife):

                    self.name           = name

                    self.diameter       = diameter

                    self.moonCount      = moonCount

                    self.surfaceGravity = surfaceGravity

                    self.orbitalPeriod  = orbitalPeriod

                    self.supportsLife   = supportsLife

    def spin():

                    print("Spinning")

    def attract():

                    print("Attracting masses")

# Create an Earth

            planetEarth = Planet("Earth", 12756, 1, 9.807, 365, True)

# Check whether the object Earth has a price attribute

            hasAPrice = hasattr(planetEarth, "Price")

            print("Earth has a price:%s"%hasAPrice)

hasAPrice = hasattr(planetEarth, "supportsLife")

            print("Does Earth supports life:%s"%hasAPrice)

Output

Output
Earth has a price:False

Does Earth supports life:True

Example 2 - Check for the existence of a method on a Python object

python
# Example Python program that checks

            # for the presence of methods in an object

            # through hasattr()

# Definition of the class Room

            class Room:

                def __init__(self, purpose):

                    self.purpose = purpose

                def info(self):

                    print("Room:%s"%self.purpose)

                def entry():

                    print("Room entered")

    def exit():

                    print("Room exited")

# Definition of the class House

            class House:

                def __init__(self, rooms, address):

                    self.rooms      = rooms

                    self.address    = address

                def info(self):

                    print("Room count:%d"%len(self.rooms))

                    print("Address:%s"%self.address)

                def enter():

                    print("Entered");

    def exit():

                    print("Exited");

# Create rooms

            rooms = [];

            for num in range(1, 4):

                rooms.append(Room(num))

# Create a house

            address = "Number 5, Privet Drive, Little Whinging, Surrey"

            house   = House(rooms, address)

# Check for the presence of the info method

            attribName      = "info"

            attribPresence  = hasattr(house, "info")

            if attribPresence is True:

                house.info()

# Check whether these sort of houses could fly

            attributeName       = "fly"

            attribPresence      = hasattr(house, attributeName)

print("House object has a fly method:%s"%attribPresence);

if attribPresence is True:

                house.fly() # Will not be entered

Output

Output
Room count:3

Address:Number 5, Privet Drive, Little Whinging, Surrey

House object has a fly method:False