-
Abre el editor de VS Code en el entorno de LabEx.
-
Crea un nuevo archivo llamado hasattr_example.py
en el directorio ~/project
.
touch ~/project/hasattr_example.py
-
Abre el archivo hasattr_example.py
en el editor y agrega el siguiente código:
import math
## Check if the 'sqrt' function exists in the 'math' module
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.")
## Check if the 'pi' constant exists in the 'math' module
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.")
## Check for a non-existent attribute
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.")
En este código, primero importamos el módulo math
. Luego, usamos hasattr()
para comprobar si la función sqrt
y la constante pi
existen en el módulo math
. También comprobamos la existencia de un atributo que no existe para ver cómo hasattr()
maneja ese caso.
-
Ejecuta el script utilizando el siguiente comando en la terminal:
python ~/project/hasattr_example.py
Deberías ver la siguiente salida:
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.
Esta salida demuestra cómo se puede usar hasattr()
para comprobar la existencia de funciones y constantes dentro de un módulo.
-
Ahora, intentemos usar hasattr()
con un objeto personalizado. Modifica el script de la siguiente manera:
class MyClass:
def __init__(self):
self.attribute1 = "Hello"
def my_method(self):
return "World"
obj = MyClass()
## Check if the object has the attribute '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'.")
## Check if the object has the method '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'.")
## Check for a non-existent attribute
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'.")
-
Vuelve a ejecutar el script:
python ~/project/hasattr_example.py
Deberías ver la siguiente salida:
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'.
Esto muestra cómo hasattr()
también se puede utilizar para comprobar la existencia de atributos y métodos en objetos personalizados.