Python hasattr() Function

The hasattr() function in Python is used to check whether the specified attribute is available in an object or not. This function returns True, if the specified attribute is available in a given object, otherwise returns False. For example:

class fresherearth:
    Course = "Computer Science"
    Language = "Python"
    Chapter = "Function"
    Topic = "hasattr()"

print(hasattr(fresherearth, "Chapter"))
print(hasattr(fresherearth, "Example"))

The output will be:

True
False

Python hasattr() Function Syntax

The syntax of hasattr() function in Python, is:

hasattr(object, attribute)

Python hasattr() Function Example

Let's create an example program demonstrating the hasattr() function in Python. This program allows user to enter the name of attribute to check whether the attribute is available in the object (class) named fresherearth or not:

class fresherearth:
    Course = "Computer Science"
    Language = "Python"
    Chapter = "Function"
    Topic = "hasattr()"

print("Enter the Attribute Name: ", end="")
attr = input()
if hasattr(fresherearth, attr):
    print("\nThe given attribute is available.")
else:
    print("\nThe given attribute is not available.")

The snapshot given below shows the sample run of above program, with user input Language:

Python hasattr function

Python Online Test


« Previous Function Next Function »