hasattr(): checking if an object has a certain attribute in Python

The hasattr() function checks if an object has a certain attribute.

The first argument is the object being checked and the second argument is the attribute.

If the attribute exists in the object the method returns True, otherwise it returns False.

In this example, I’m defining a class Vehicle with four attributes year, model, plate_number, and current_speed.

Then I instantiate an object vehicle.

Finally I use the hasattr() to check if vehicle has the attributes model (returns True) and color (returns False).

class Vehicle:
    def __init__(self, year, model, plate_number, current_speed):
        self.year = year
        self.model = model
        self.plate_number = plate_number
        self.current_speed = current_speed

vehicle = Vehicle(2009, 'F8', 'ABC1234', 100)

print(hasattr(vehicle, 'model'))

print(hasattr(vehicle, 'color'))
True

False