Python hasattr()
is a built-in function that returns true if the object has given attribute and false if the object doesn’t have given attribute.
hasattr(object, name)
Python hasattr()
function takes two parameters.
hasattr()
will return true
if the object has the named attribute else it will return false
.
hasattr()
is implemented by calling getattr()
function and checking whether or not it raises AttributeError
.
>>> class Car:
def __init__(self,model):
self.model = model
>>> hasattr(obj, 'model')
True
>>> hasattr(obj, 'price')
False
As you can see in above example, hasattr()
function returns true
when object has the named attribute (ie. model
in above example) and false
when attribute is not available.