Python hasattr()

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

Example

class Person:
    age = 23
    name = "Adam"

person = Person()

print("Person's age:", hasattr(person, "age"))
print("Person's salary:", hasattr(person, "salary"))

# Output:
# Person's age: True
# Person's salary: False

hasattr() Syntax

The syntax of the hasattr() method is:

hasattr(object, name)

hasattr() Parameters

The hasattr() method takes two parameters:

  • object - object whose named attribute is to be checked
  • name - name of the attribute to be searched

hasattr() Return Value

The hasattr() method returns:

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

Example: Python hasattr()

class Car:
    brand = "Ford"
    number = 7786

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

In the above example, we have a Car class with two attributes: brand and number.

When we check for these two attributes using the hasattr() method, the result is True.

On the other hand, for any attribute not in the class Car such as specs, we get False as the output.


Recommended Readings:

Did you find this article helpful?