Python hasattr() Method
hasattr() method checks if an object of the class has the specified attribute.
- object: Required. The object whose attribute is to be checked.
- name: Required. Name of the attribute.
Returns True if an object has the specified attribute else returns False.
The following example checks whether the built-in class
str contains specified attributes or not.
print('str has title: ', hasattr(str, 'title')) print('str has __len__: ', hasattr(str, '__len__')) print('str has isupper method: ', hasattr(str, 'isupper')) print('str has isstring method: ', hasattr(str, 'isstring'))
str has title: True str has len: True str has isupper method: True str has isstring method: False
hasattr() method can also be used with the user-defined classes, as shown below.
class student: name = "John" age = "18" print("student has name: ", hasattr(student,"name")) print("student has age: ", hasattr(student,"age")) print("student has address: ", hasattr(student,"address"))
student has name: True student has age: True student has address: False