Hasattr Function In Python


  • 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:

# 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():            

    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)


Earth has a price:False

Does Earth supports life:True

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

# 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):
    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))
    def enter():

    def exit():

# Create rooms
rooms = [];
for num in range(1, 4):

# 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:

# 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



Room count:3

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

House object has a fly method:False

Copyright 2022 © pythontic.com