티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Determine the type of an object?
가장 효율적인 변수 타입 확인 방법
문제 내용
Is there a simple way to determine if a variable is a list, dictionary, or something else?
변수가 리스트인지 Dictionary인지 아니면 다른 것인지를 확인하는 간단한 방법이 있나요?
높은 점수를 받은 Solution
There are two built-in functions that help you identify the type of an object. You can use type()
if you need the exact type of an object, and isinstance()
to check an object’s type against something. Usually, you want to use isinstance()
most of the times since it is very robust and also supports type inheritance.
개체 유형을 식별하는 데 도움이 되는 두 가지 기본 제공 기능이 있습니다. 개체의 정확한 유형이 필요한 경우 type()을 사용할 수 있으며, isinstance()는 개체의 유형을 확인하는 데 사용됩니다. 일반적으로 isinstance()는 매우 강력하고 유형 상속도 지원하므로 대부분 사용하고자 합니다.
To get the actual type of an object, you use the built-in type()
function. Passing an object as the only parameter will return the type object of that object:
개체의 실제 유형을 가져오려면 기본 제공 type() 함수를 사용합니다. 개체를 유일한 매개 변수로 전달하면 해당 개체의 형식 개체가 반환됩니다.
>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True
This of course also works for custom types:
물론 이는 사용자 정의 유형에도 적용됩니다.
>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True
Note that type()
will only return the immediate type of the object, but won’t be able to tell you about type inheritance.
type()은 객체의 즉시 형식만 반환하지만 형식 상속에 대해서는 알려줄 수 없습니다.
>>> type(b) is Test1
False
To cover that, you should use the isinstance
function. This of course also works for built-in types:
그것을 커버하려면 isinstance 기능을 사용해야 합니다. 물론 이 기능은 다음과 같은 내장형에도 사용할 수 있습니다.
>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True
isinstance()
is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance()
is preferred over type()
.
isinstance()는 파생된 형식도 허용하기 때문에 일반적으로 개체의 형식을 보장하는 데 선호되는 방법입니다. 따라서 어떤 이유로든 형식 개체가 실제로 필요하지 않은 경우에는 type()보다 isinstance()를 사용하는 것이 좋습니다.
The second parameter of isinstance()
also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance
will then return true, if the object is of any of those types:
isinstance()의 두 번째 매개 변수는 튜플 타입도 허용하므로 여러 유형을 한 번에 확인할 수 있습니다. 개체가 다음 유형 중 하나일 경우 is 인스턴스는 true를 반환합니다.
>>> isinstance([], (tuple, list, set))
True
가장 최근 달린 Solution
using type()
type() 사용
x='hello this is a string'
print(type(x))
output
결과
<class 'str'>
to extract only the str use this
str만 추출하려면 아래를 사용하세요.
x='this is a string'
print(type(x).__name__)#you can use__name__to find class
output
결과
str
if you use type(variable).__name__
it can be read by us
type(variable).__name__ 을 사용하면 우리가 읽을 수 있습니다
출처 : https://stackoverflow.com/questions/2225038/determine-the-type-of-an-object
'개발 > 파이썬' 카테고리의 다른 글
장고 앱 이름 바꾸기 (0) | 2022.12.03 |
---|---|
Dictionary에서 아이템(요소) 삭제 (0) | 2022.12.02 |
값 기준으로 Dictionary 정렬하기 (0) | 2022.12.02 |
리스트의 마지막 아이템을 가져오는 가장 효과적인 방법 (0) | 2022.12.02 |
리스트를 같은 크기의 청크로 분할하기 (0) | 2022.12.02 |