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 CodesCracker:
    Course = "Computer Science"
    Language = "Python"
    Chapter = "Function"
    Topic = "hasattr()"

print(hasattr(CodesCracker, "Chapter"))
print(hasattr(CodesCracker, "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 CodesCracker or not:

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

print("Enter the Attribute Name: ", end="")
attr = input()
if hasattr(CodesCracker, 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 »



Like/Share Us on Facebook 😋