자료형 다루기

자료형이 어떤 타입인지, 어떤 클래스의 인스턴스인지 알아보는 방법

어떤 타입인지 확인 type(value)

  • 반환값: <type 타입이름>

  • str

  • float

  • int

>>> s = "hello"
>>> type(s) # <type 'str'>

>>> f = 3.14
>>> type(f) # <type 'float'>

>>> i = 42
>>> type(i) # <type 'int'>

>>> my_list = [1, 2, 3]
>>> my_dict = {"풀": 800, "색연필": 3000}
>>> my_tuple = (1, 2, 3)
>>> print(type(my_list))     #<type 'list'>
>>> print(type(my_dict))     #<type 'dict'>
>>> print(type(my_tuple))    #<type 'tuple'>

인스턴스인지 아닌지 확인 isinstance(value, typeName)

  • 반환값: boolean

>>> isinstance(42, int)
True
>>> isinstance(42, float)
False

같은 인스턴스인지를 확인하는 연산자 is

list1 = list("hello")
list2 = list("hello")

isinstance(list1, list)      #True
isinstance(list2, list)      #True

print(list1 == list2)        #True     list1과 list2는 같은 값을 가집니다.
print(list1 is list2)        #False    list1과 list2는 다른 인스턴스입니다.

클래스의 상속을 검사하기 issubclass(class, classinfo)

  • class가 classinfo의 서브클래스면 참을 돌려준다.

Last updated