-
LabEx 환경에서 VS Code 편집기를 엽니다.
-
~/project 디렉토리에 hasattr_example.py라는 새 파일을 만듭니다.
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()를 사용하여 사용자 정의 객체의 속성 및 메서드를 확인하는 방법도 보여줍니다.