-
Ouvrez l'éditeur VS Code dans l'environnement LabEx.
-
Créez un nouveau fichier nommé hasattr_example.py
dans le répertoire ~/project
.
touch ~/project/hasattr_example.py
-
Ouvrez le fichier hasattr_example.py
dans l'éditeur et ajoutez le code suivant :
import math
## Vérifie si la fonction 'sqrt' existe dans le module 'math'
if hasattr(math, 'sqrt'):
print("The 'sqrt' function exists in the 'math' module.")
result = math.sqrt(25)
print("The square root of 25 is:", result)
else:
print("The 'sqrt' function does not exist in the 'math' module.")
## Vérifie si la constante 'pi' existe dans le module 'math'
if hasattr(math, 'pi'):
print("The 'pi' constant exists in the 'math' module.")
print("The value of pi is:", math.pi)
else:
print("The 'pi' constant does not exist in the 'math' module.")
## Vérifie pour un attribut non existant
if hasattr(math, 'non_existent_attribute'):
print("The 'non_existent_attribute' exists in the 'math' module.")
else:
print("The 'non_existent_attribute' does not exist in the 'math' module.")
Dans ce code, nous importons d'abord le module math
. Ensuite, nous utilisons hasattr()
pour vérifier si la fonction sqrt
et la constante pi
existent dans le module math
. Nous vérifions également pour un attribut non existant pour voir comment hasattr()
gère ce cas.
-
Exécutez le script en utilisant la commande suivante dans le terminal :
python ~/project/hasattr_example.py
Vous devriez voir la sortie suivante :
The 'sqrt' function exists in the 'math' module.
The square root of 25 is: 5.0
The 'pi' constant exists in the 'math' module.
The value of pi is: 3.141592653589793
The 'non_existent_attribute' does not exist in the 'math' module.
Cette sortie démontre comment hasattr()
peut être utilisé pour vérifier l'existence de fonctions et de constantes dans un module.
-
Maintenant, essayons d'utiliser hasattr()
avec un objet personnalisé. Modifiez le script comme suit :
class MyClass:
def __init__(self):
self.attribute1 = "Hello"
def my_method(self):
return "World"
obj = MyClass()
## Vérifie si l'objet a l'attribut 'attribute1'
if hasattr(obj, 'attribute1'):
print("The object has the attribute 'attribute1'.")
print("The value of attribute1 is:", obj.attribute1)
else:
print("The object does not have the attribute 'attribute1'.")
## Vérifie si l'objet a la méthode 'my_method'
if hasattr(obj, 'my_method'):
print("The object has the method 'my_method'.")
print("The result of my_method is:", obj.my_method())
else:
print("The object does not have the method 'my_method'.")
## Vérifie pour un attribut non existant
if hasattr(obj, 'non_existent_attribute'):
print("The object has the attribute 'non_existent_attribute'.")
else:
print("The object does not have the attribute 'non_existent_attribute'.")
-
Exécutez le script à nouveau :
python ~/project/hasattr_example.py
Vous devriez voir la sortie suivante :
The object has the attribute 'attribute1'.
The value of attribute1 is: Hello
The object has the method 'my_method'.
The result of my_method is: World
The object does not have the attribute 'non_existent_attribute'.
Cela montre comment hasattr()
peut également être utilisé pour vérifier l'existence d'attributs et de méthodes dans des objets personnalisés.