-
Откройте редактор VS Code в среде LabEx.
-
Создайте новый файл с именем hasattr_example.py
в директории ~/project
.
touch ~/project/hasattr_example.py
-
Откройте файл hasattr_example.py
в редакторе и добавьте следующий код:
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.")
В этом коде мы сначала импортируем модуль math
. Затем используем hasattr()
для проверки наличия функции sqrt
и константы pi
в модуле math
. Также проверяем несуществующий атрибут, чтобы увидеть, как hasattr()
обрабатывает такой случай.
-
Запустите скрипт с помощью следующей команды в терминале:
python ~/project/hasattr_example.py
Вы должны увидеть следующий вывод:
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.
Этот вывод демонстрирует, как можно использовать hasattr()
для проверки наличия функций и констант в модуле.
-
Теперь попробуем использовать hasattr()
с пользовательским объектом. Измените скрипт следующим образом:
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'.")
-
Запустите скрипт еще раз:
python ~/project/hasattr_example.py
Вы должны увидеть следующий вывод:
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'.
Это показывает, как hasattr()
также можно использовать для проверки наличия атрибутов и методов в пользовательских объектах.