Python hasattr() FunctionPython Functions

Difficulty Level:
Difficulty Level:

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.

Advertisement

© 2021 Pythonexample.org, all rights reserved. Privacy Policy | Contact Us