Python hasattr() Function

Python hasattr() is a built-in function that returns true if the object has given attribute and false if the object doesn’t have given attribute.

python hasattr() function

Python hasattr() Syntax

hasattr(object, name)

Python hasattr() function takes two parameters.

  • object – The object which is to be searched for the availability of the attribute.
  • name – Name of the attribute to be searched for.

hasattr() will return true if the object has the named attribute else it will return false.

hasattr() is implemented by calling getattr() function and checking whether or not it raises AttributeError.

Python hasattr() Example

>>> class Car:
      def __init__(self,model):
        self.model = model

>>> hasattr(obj, 'model')

>>> hasattr(obj, 'price')

As you can see in above example, hasattr() function returns true when object has the named attribute (ie. model in above example) and false when attribute is not available.