Python hasattr() Function



The Python hasattr() function is a built-in function that checks whether an object contains the specified attribute. This function returns True if the attribute exists, and False otherwise.

We can use this function when we want to ensure that an attribute exists before accessing it, which can help in preventing runtime errors.

In the next few sections, we will be exploring this function in more detail.

Syntax

The syntax of the Python hasattr() function is as follows −

hasattr(object, attribute)

Parameters

The following are the parameters of the python hasattr() function −

  • object − This parameter specifies the object whose named attribute needs to be checked.

  • attribute − This parameter represents a string that is to be searched in the specified object.

Return Value

The Python hasattr() function returns a Boolean value.

Examples

To understand the working of hasattr() function, see the below examples −

Example 1

The following is an example of the Python hasattr() function. In this, we have defined a class and instantiated its object and, trying to verify if it contains the specified attribute or not.

class Car:
   wheels = 4

transport = Car()
output = hasattr(transport, "wheels") 
print("The car has wheels:", output)

On executing the above program, the following output is generated −

The car has wheels: True

Example 2

The hasattr() function can also check inherited attributes with ease. In the code below, we have defined a parent class and its subclass. Then, using the hasattr() function, we are checking whether the subclass is able to inherit the attribute of its parent class.

class Car:
   wheels = 4

class Tata(Car):
   fuelType = "Petrol"

newCar = Tata()
output = hasattr(newCar, "wheels") 
print("The new car has wheels:", output)

The following is the output obtained by executing the above program −

The new car has wheels: True

Example 3

If the specified attribute is not available in the given object, the hasattr() function will return false. Here, the passed attribute does not belong to any of the defined classes. Hence, the result will be False.

class Car:
    wheels = 4

class Tata(Car):
    fuelType = "Petrol"

newCar = Tata()
output = hasattr(newCar, "wings") 
print("The new car has wheels:", output)

The following output is obtained by executing the above program -

The new car has wheels: False

Example 4

In the following example, we are using the hasattr() function to verify if the given method is defined in the specified class or not.

class AI:
   def genAI(self):
      pass

chatGpt = AI()
output = hasattr(chatGpt, "genAI")
print("The chat GPT is genAI:", output)

The above program, on executing, displays the following output −

The chat GPT is genAI: True
python_built_in_functions.htm
Advertisements