파이썬에서 type()
과 isinstance()
함수로 객체의 타입을 확인할 수 있습니다.
1. type() : 인자로 전달된 객체의 타입을 리턴
type()
은 인자로 전달된 타입을 리턴하며, print()
로 출력할 수 있습니다.
print(type(123))
print(type(123.4))
print(type('str'))
my_list = ['a', 'b']
print(type(my_list))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
1.1 If문에서 타입 체크
다음과 같이 조건문에서 타입 체크를 할 수 있습니다.
my_list = ['a', 'b']
if type(my_list) is list:
print("It's list")
if type(123) is int:
print("It's int")
if type(123.4) is float:
print("It's float")
if type('str') is str:
print("It's str")
Output:
It's list
It's int
It's float
It's str
2. isinstance() : type과 일치하는지 type의 subclass인지 확인
isinstance()
는 인자로 전달된 객체가 type과 일치하는지, 또는 type의 subclass인지 true/false로 리턴합니다.
print(isinstance(123, int))
print(isinstance(123.4, float))
print(isinstance('str', str))
my_list = ['a', 'b']
print(isinstance(my_list, list))
Output:
True
True
True
True
2.1 If문에서 타입 체크
다음과 같이 조건문에서 타입 체크를 할 수 있습니다.
if isinstance(123, int):
print("It's int")
if isinstance(123.4, float):
print("It's float")
if isinstance('str', str):
print("It's str")
Output:
It's int
It's float
It's str
Loading script...
Related Posts
- Python 소수점 반올림, round() 예제
- 파이썬 주석 처리, 단축키 소개
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 정리 및 예제
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 디폴트 매개변수(Default parameters)
- Python - filter() 사용 방법 및 예제