Skip to main content

Python hasattr() Function

The hasattr() method returns true if an object has the given named attribute and false if it does not.

Syntax

hasattr(object, name)

hasattr() Parameters

Python hasattr() function parameters:

ParameterConditionDescription
objectRequiredObject whose named attribute is to be checked
nameRequiredName of the attribute you want to check if exists

hasattr() Return Value

Python hasattr() function returns:

  • True if object has the given named attribute
  • False if object has no given named attribute

Example: simple example with hasattr() function

For example, let's check if some attributes are in the Car class:

class Car:
brand = "Ford"
number = 12345

car = Car()

print("The car class has brand:", hasattr(Car, "brand"))
print("The car class has specs: ", hasattr(Car, "specs"))

output

The car class has brand: True
The car class has specs: False

Note:

  • If the attribute is in the class, then the result of hasattr() is True.
  • If the attribute is not in the class, then the result of hasattr() is False.