BlogsDope image BlogsDope

Python hasattr() function

Feb. 28, 2021 PYTHON FUNCTION 824

Python provides a large number of utility functions that help in many day-to-day programming applications. One of these functions is the hasattr() function. The hasattr() function checks if an object has the given named attribute, and returns true if the attribute is present, else it returns false.

Python hasattr() Syntax

The syntax of hasattr() method is as follows:

​hasattr(object, name)

hasattr() Parameters

The hasattr() method takes the following two parameters:
  1. object - This parameter is the object whose named attribute is to be checked by the hasattr() function.
  2. name - This parameter is the name of the attribute to be checked within the object.

hasattr() Return Value

​​The hasattr() method returns two values -

Return Value
Details
True
The attribute is present in the given object.
False
The attribute is not present in the given object.

hasattr() Example

class CodesDope:
    name = 'Sam'
    marks = 50

obj = CodesDope()
print("Does the object have attribute name?:",str(hasattr(obj,'name')))
print("Does the object have attribute marks?:",str(hasattr(obj,'marks')))
print("Does the object have attribute age?:",str(hasattr(obj,'age')))

Output:

​Does the object have attribute name?: True
Does the object have attribute marks?: True
Does the object have attribute age?: False

In this way we have seen the working of the Python hasattr() function and how it can be used to check if a certain attribute exists in our object or not.

Liked the post?
Zealous Learner.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).