Python – Check if Object has a Specific Attribute

Python – Check if Object has Specific Attribute

To check if given Python object has a specific attribute, call hasattr() builtin function, and pass object and the attribute name to the hasattr() function. If the object has the specified attribute, then hasattr() function returns True, else it returns False.

The following program statement is an example to call hasattr() function to check if given Python object object has a specific attribute attrName.

hasattr(object, attrName)

hasattr() returns boolean value of True or False.

Example 1: Check if Python Object has Specific Attribute

In this example, we will take an object A1 with attributes x and y. We will then use hasattr() function to check if A1 has attribute x and z.

Python Program

class A:
    def __init__(self, x, y):
        self.x = x
        self.y = y


A1 = A(2, 3)

result = hasattr(A1, 'x')
print(f'Does A1 has x? {result}')
result = hasattr(A1, 'z')
print(f'Does A1 has z? {result}')
Run Code Copy

Output

Does A1 has x? True
Does A1 has z? False

Summary

In this tutorial of Python Examples, we learned how to check if given Python object has a specific attribute, using hasattr() function.

Code copied to clipboard successfully 👍