🐍Python | Django
[Python] Type Check - type(), isinstance()
이줭
2022. 5. 18. 11:03
728x90
type()
type()의 경우 파이썬에서 기본적으로 제공하는 자료형에 대해 type check가 가능하다.
type(1) is int # True
type([]) is list # True
type('abc') is str # True
type(1) is type(2) # True
하지만, type()은 상속의 경우가 고려되지 않아 상속받은 클래스의 인스턴스는 구분할 수 없다.
class A():
pass
class B(A):
pass
a = A()
b = B()
type(a) is A # True
type(b) is B # True
type(b) is A # False
이러한 문제를 해결하기 위해서는 어떤 메서드를 사용해야 할까?
isInstance()
type()의 한계점을 isInstance()로 해결할 수 있고, 사용법은 아래와 같다.
class A():
pass
class B(A):
pass
a = A()
b = B()
isInstance(a, A) # True
isInstance(b, B) # True
isInstance(b, A) # True
그래서 어떤 걸 사용하라고요 🙋♂️
type()과 isInstance()는 특징이 다른 것이지 장단점이 있는 것이 아니기 때문에 적절히 활용하는 것이 좋다.
728x90