Hasattr Function in Python

In Python, the hasattr() function allows you to check if a class has an attribute with a specific name.

Syntax

hasattr(class_name, attribute_name)

The first argument is the name of the class, and the second is the string name of the attribute you're looking for.

The function returns a boolean value:

  • True if the class contains an attribute with the specified name.
  • False if the attribute does not exist in the class.

    A Practical Example

    Let's create a class called Prova with a method named method1.

    1. class Prova:
    2. def method1(self):
    3. print('ciao')
    4. return self._name

    Next, we'll use the hasattr function to check if the Prova class contains the attribute 'method1'.

    hasattr(Prova, 'method1')

    The function returns True because the attribute 'method1' exists in the Prova class.

    True

    Now, let's use the same function to check if it also contains the attribute 'method2'.

    hasattr(Prova, 'method2')

    The function returns False because the attribute 'method2' does not exist in the class.

    False

    This way, you can confirm whether a specific attribute exists in a class before trying to use it.

    And that's it!

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python Classes