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:
# Example Python program that checks an object for an attribute # A simple definition of a Planet class def spin(): def attract(): # Create an Earth # Check whether the object Earth has a price attribute hasAPrice = hasattr(planetEarth, "supportsLife") |
Output:
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 # Definition of the class Room def exit(): # Definition of the class House def exit(): # Create rooms # Create a house # Check for the presence of the info method # Check whether these sort of houses could fly print("House object has a fly method:%s"%attribPresence); if attribPresence is True: |
Output:
Room count:3 Address:Number 5, Privet Drive, Little Whinging, Surrey House object has a fly method:False |