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.
- class Prova:
- def method1(self):
- print('ciao')
- 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!