-
Abra o editor VS Code no ambiente LabEx.
-
Crie um novo arquivo chamado hasattr_example.py no diretório ~/project.
touch ~/project/hasattr_example.py
-
Abra o arquivo hasattr_example.py no editor e adicione o seguinte 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.")
Neste código, primeiro importamos o módulo math. Em seguida, usamos hasattr() para verificar se a função sqrt e a constante pi existem no módulo math. Também verificamos um atributo inexistente para ver como hasattr() lida com esse caso.
-
Execute o script usando o seguinte comando no terminal:
python ~/project/hasattr_example.py
Você deve ver a seguinte saída:
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 saída demonstra como hasattr() pode ser usado para verificar a existência de funções e constantes dentro de um módulo.
-
Agora, vamos tentar usar hasattr() com um objeto personalizado. Modifique o script da seguinte forma:
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'.")
-
Execute o script novamente:
python ~/project/hasattr_example.py
Você deve ver a seguinte saída:
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'.
Isso mostra como hasattr() também pode ser usado para verificar atributos e métodos em objetos personalizados.