Python hasattr() function
Python hasattr() function
The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False.
Syntax
hasattr(object, name)
Parameter
object: it is a required parameter which represents an object.
attribute: This parameter represents the name of the attribute you want to check if it exists.
Return
This function returns a Boolean value ‘True’ if the given object has the specified attribute
Example 1
# Python Program explaining # the hasattr() function class Student: student = "John" marks = 36 val = hasattr(Student, 'marks') print(val)
Output
True
Example 2
# Python Program explaining # the hasattr() function class Example : name = "TutorialsAndExamples" age = 14 # initializing object val = Example() # using hasattr() to check name print ("Name attribute exists in the class: " + str(hasattr(val, 'name')))
Output
Name attribute exists in the class: True