hasattr() Function in Python

Python hasattr() Function

The hasattr() function is a built-in function in Python that allows you to check if an object has a particular attribute or method. It takes two arguments: the object to be checked and a string representing the name of the attribute or method.

Here's the syntax of the hasattr() function:

hasattr(object, attribute)
  • object: The object you want to check for the attribute or method.
  • attribute: A string representing the name of the attribute or method.

The hasattr() function returns a Boolean value, True if the object has the specified attribute or method, and False otherwise.

Here's an example to illustrate the usage of hasattr():

class MyClass:
    def __init__(self):
        self.attribute = 42
    
    def method(self):
        print("Hello, world!")

obj = MyClass()

print(hasattr(obj, 'attribute'))  # True
print(hasattr(obj, 'method'))     # True
print(hasattr(obj, 'nonexistent')) # False

In the above example, hasattr(obj, 'attribute') returns True because the obj instance of the MyClass class has an attribute called attribute. Similarly, hasattr(obj, 'method') returns True because obj has a method called method. On the other hand, hasattr(obj, 'nonexistent') returns False because obj doesn't have an attribute or method with the name nonexistent.