isinstance() 함수로 확인하기
이 단계에서는 Python 에서 isinstance() 함수를 사용하여 객체가 특정 클래스의 인스턴스인지 확인하는 방법을 배우게 됩니다. 이것은 변수가 Boolean 값을 가지고 있는지 확인하는 또 다른 방법입니다. isinstance() 함수는 두 개의 인수를 받습니다: 확인할 객체와 비교할 클래스입니다. 객체가 해당 클래스의 인스턴스인 경우 True를 반환하고, 그렇지 않으면 False를 반환합니다.
isinstance()를 사용하여 변수가 Boolean 인지 확인해 보겠습니다.
-
VS Code 편집기를 사용하여 ~/project 디렉토리에서 boolean_example.py 파일을 엽니다.
-
boolean_example.py 파일을 수정하여 isinstance() 함수를 포함합니다.
## 변수에 True 할당
is_active = True
## 변수에 False 할당
is_admin = False
## 값 출력
print("Is active:", is_active)
print("Is admin:", is_admin)
## 비교 연산
x = 10
y = 5
is_greater = x > y ## 10 이 5 보다 크기 때문에 True
is_equal = x == y ## 10 이 5 와 같지 않기 때문에 False
print("Is x greater than y:", is_greater)
print("Is x equal to y:", is_equal)
## 변수의 유형 확인
print("Type of is_active:", type(is_active))
print("Type of is_greater:", type(is_greater))
print("Type of x:", type(x))
## 변수가 bool 클래스의 인스턴스인지 확인
print("is_active is an instance of bool:", isinstance(is_active, bool))
print("x is an instance of bool:", isinstance(x, bool))
-
파일을 저장합니다.
-
터미널에서 python 명령을 사용하여 스크립트를 실행합니다.
python ~/project/boolean_example.py
다음과 같은 출력을 볼 수 있습니다.
Is active: True
Is admin: False
Is x greater than y: True
Is x equal to y: False
Type of is_active: <class 'bool'>
Type of is_greater: <class 'bool'>
Type of x: <class 'int'>
is_active is an instance of bool: True
x is an instance of bool: False
보시다시피, isinstance(is_active, bool)은 is_active가 Boolean 값이므로 True를 반환하는 반면, isinstance(x, bool)은 x가 정수이므로 False를 반환합니다. isinstance() 함수는 변수가 특정 클래스에 속하는지 확인하는 데 유용하며, 데이터 유형을 확인하는 보다 강력한 방법을 제공합니다.