728x90
반응형
"Life is too short, You need python"
파이썬에서 특히 초심자들이 애를 먹는 부분이자 많이 접하는 에러 메시지 중 하나가 'xxx' object has no attribute 'xxx'입니다. 데이터 타입(Data Type)에 따라 사용 가능한 함수가 있지만 어느 정도 익숙해 지기까지는 많이 혼란스럽습니다. 오류가 발생했을 때 data type을 항상 확인해서 문제를 해결하는 습관을 가진다면 금세 해결될 수 있을 거라 생각합니다.
type(), isinstance()
파이썬에서는 아래의 두 함수를 이용하여 객체의 타입을 확인할 수 있습니다.
- type() : parameter로 전달된 객체(object)의 타입(type)을 반환(return)
- isinstance() : type과 일치하는지 type의 subclass인지 확인
type() : 자료 유형 확인
type( obj ) : type 함수는 object의 class type을 알고 싶을 때 사용하는 함수입니다. 대부분의 경우 디버깅 목적으로 사용하는데 직접 또는 변수를 통해 parameter로 전달된 object의 타입을 리턴하며, print()로 결과를 출력할 수 있습니다.
( Input )
print(type(456))
print(type(456.7))
print(type('string'))
my_list = ['1', '2', 'a', 'b']
print(type(my_list))
( Output )
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
type 함수와 if문을 통해 타입 체크
type 함수를 사용해서 자료형을 비교할 때 if문을 많이 사용합니다.
( Input )
# 자료형의 Class명을 직접 입력하여 비교
my_list = ['1', '2', 'a', 'b']
if type(my_list) is list:
print("It's list")
if type(456) is int:
print("It's int")
if type(456.7) is float:
print("It's float")
if type('str') is str:
print("It's str")
# 참조 비교 연산자인 is 를 함께 사용
dict_type = {4:'c', 5:'d', 6:'e'}
list_type = [4, 5, 6, 7, 8, 9]
if type(dict_type) is not type(list_type):
print('different type')
else:
print('same type')
# 리턴 값을 str 함수로 문자열 변환해서 비교
int_type = 1
if str(type(int_type)) == "<class 'int'>":
print('int type')
else:
print('not int type')
( Output )
It's list
It's int
It's float
It's str
different type
int type
isinstance() : type과 일치여부, type의 subclass인지 확인
isinstance( object, class/data type )
isinstance()는 parameter로 전달된 object가 type과 일치하는지 여부를 확인하거나, subclass인지 여부를 true/false로 반환합니다
( Input )
print(isinstance(456, int))
print(isinstance(456.78, float))
print(isinstance('string', str))
my_list = ['4', '5', 'c', 'e']
print(isinstance(my_list, list))
( Output )
True
True
True
True
마무리
type(), isinstance() 함수를 활용하여 데이터 타입을 확인하는 방법에 대해 알아보았습니다.
728x90
반응형