Computer >> Computer tutorials >  >> Programming >> Python

How to know if an object has an attribute in Python?


We can use hasattr() function to find if a python object obj has a certain attribute or property. 

hasattr(obj, 'attribute'):

The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block. If the property is likely to not be there or if you're not sure, using hasattr will probably be a better option.

The following code shows how to check if the class foo has an attribute 'a'.

Example

class foo:
    a = 54
    def bar(self):
        pass
if hasattr(foo, 'a'):
   print foo.a
else:
   print 'No such attribute'

Output

54