Tutorial Study Image

Python hasattr()

The hasattr() method helps to check the given object has the specified attribute. If the attribute is present it returns true otherwise return false.


hasattr(object, name)  #Where object,name shows object name and attribute name respectively.
 

hasattr() Parameters:

Takes 3 parameters . The method hasattr() is called by getattr()  to check to see if AttributeError is to be raised or not. The getattr() is used to get the value of a specified object’s attribute.

Parameter Description Required / Optional
object  object whose named attribute is to be checked Required
name  name of the attribute to be searched Required

hasattr() Return Value

The return value depends on getattr() function. If it has thrown AttributeError then False is returned. Otherwise, True is returned.

Input Return Value
the object has the given named attribute True
the object has no given named attributer False

Examples of hasattr()  method in Python

Example 1: How hasattr() works in Python?


class Person:
    age = 23
    name = 'Adam'
 pers

print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))
 

Output:

Person has age?: True
Person has salary?: False

Example 2: How hasattr() works with employe example?


class Employee:
    id = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n


d = Employee(10, 'Pankaj')

if hasattr(d, 'name'):
    print(getattr(d, 'name'))
 

Output:

Pankaj

Example 3: How hasattr() return boolean values?


class Employee:  
    age = 21  
    name = 'Phill'  
  
employee = Employee()  
  
print('Employee has age?:', hasattr(employee, 'age'))  
print('Employee has salary?:', hasattr(employee, 'salary'))  
 

Output:

Employee has age?: True
Employee has salary?: False