How to Use hasattr() Function in PythonPython Basics


The hasattr() function checks if the object contains the corresponding attributes or not.

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class temp:
    a = 11
    s = -15
    d = 10

point1 = temp()
print(hasattr(point1, 'a'))
print(hasattr(point1, 's'))
print(hasattr(point1, 'd'))
print(hasattr(point1, 'f'))  # No such attribute

Output:

True
True
True
False

Syntax

hasattr(object, name)

Parameters

Name Description
object Object whose named attribute is to be checked.
name Name of the attribute to be searched.

Return Value

It returns True if the object has the named attribute, otherwise, it returns False.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us