Python hasattr()
Python hasattr() builtin function is used to check if a Python object has a specific named attribute.
In this tutorial, we will learn about the syntax of Python hasattr() function, and learn how to use this function with the help of examples.
Syntax
The syntax of hasattr() function with the Python object and the name of attribute as parameters is
hasattr(object, name)
where
Parameter | Required/Optional | Description |
---|---|---|
object | Required | A Python object. |
name | Required | A string that represents the name of attribute. |
Returns
The function returns a boolean value.
Example
In this example, we will define a class A
with attributes: x
and y
. We will use hasattr() function to check if object of type A
has attribute with name 'x'
.
Since, object A
has attribute named x
, calling hasattr() with this object and attribute name should return True.
Python Program
class A:
x = 10
y = 20
name = 'x'
obj = A
result = hasattr(obj, name)
print(f'Does the object {obj} has attribute named "{name}"? {result}')
Output
Does the object <class '__main__.A'> has attribute named "x"? True
Now, let us try to check if attribute named z
is present in the object of type A
.
Since, object A
does not have attribute named z
, calling hasattr() with this object and attribute name should return False.
Python Program
class A:
x = 10
y = 20
name = 'z'
obj = A
result = hasattr(obj, name)
print(f'Does the object {obj} has attribute named "{name}"? {result}')
Output
Does the object <class '__main__.A'> has attribute named "z"? False
Conclusion
In this Python Tutorial, we have learnt the syntax of Python hasattr() builtin function, and also learned how to use this function, with the help of Python example programs.