#Use the hasattr() Function
print(hasattr(list, 'sort'))
print(hasattr("pynerds", "capitalize"))
print(hasattr((1, 2), 'sort'))
The hasattr()
function checks whether an object has an attribute with the given name. An attribute can be a variable, method, property, data member, etc.
hasattr(obj, attr)
obj |
The object of which the attribute has to be checked |
attr |
A string specifying the name of the the attribute whose presence has to be tested in obj . |
The function returns True
if the object contains the specified attribute name, otherwise False.
Examples:
hasattr(str, 'join')
//True
hasattr(str, 'lower')
//True
hasattr(str, 'isalpha')
//True
hasattr(str, 'sort')
//False
L = []
hasattr(L, 'sort')
//True
hasattr(L, '__len__')
//True
hasattr(L, 'append')
//True
S = set()
hasattr(S, 'add')
//True
hasattr(S, 'update')
//True
Example with user defined object
class Demo:
x = 10
def demofunc():
pass
print(hasattr(Demo, 'x'))
print(hasattr(Demo, 'demofunc'))
print(hasattr(Demo, 'y'))