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
1 2 3 |
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
1 2 3 4 5 6 7 8 9 |
# Python Program explaining # the hasattr() function class Student: student = "John" marks = 36 val = hasattr(Student, 'marks') print(val) |
Output
1 2 3 |
True |
Example 2
1 2 3 4 5 6 7 8 9 10 11 |
# 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
1 2 3 |
Name attribute exists in the class: True |