Skip to content

Python hasattr() Function

Check if an object has a specific attribute in Python using the built-in hasattr() function with clear syntax, parameters, and practical examples.

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:

Parameter Condition Description
object Required Object whose named attribute is to be checked
name Required Name 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.
Navigation