Sometimes, we want to check if an object has an attribute in Python.
In this article, we’ll look at how to check if an object has an attribute in Python.
How to check if an object has an attribute in Python?
To check if an object has an attribute in Python, we can use the hasattr
function.
For instance, we write:
class A:
property = 'foo'
a = A()
if hasattr(a, 'property'):
print(a.property)
We have an A
class with the property
instance property set to 'foo'
.
Then we create a new instance of A
.
And then we call hasattr
with a
and 'property'
to check if property property
exists in a
.
Since this is True
, we see 'foo'
printed.
Conclusion
To check if an object has an attribute in Python, we can use the hasattr
function.