이 기사에서는 다음에 대해 다룰 것입니다. type() 및 isinstance() 함수 파이썬 , 그리고 차이점은 무엇인가요? 유형() 그리고 isinstance() .
Python에서 유형이란 무엇입니까?
Python에는 런타임에 프로그램에 사용되는 변수의 유형을 파악하는 데 일반적으로 유용한 type이라는 내장 메서드가 있습니다. 그만큼 입력을 확인하는 정식 방법 파이썬 다음과 같습니다:
type() 함수의 구문
type(object) type(name, bases, dict)>
예 1: 단일 개체 매개변수가 있는 type()의 예
이 예에서는 각 변수의 데이터 유형을 확인하려고 합니다. x, s, y와 같은 유형() 함수 .
파이썬3
# Python code type() with a single object parameter> x>=> 5> s>=> 'geeksforgeeks'> y>=> [>1>,>2>,>3>]> print>(>type>(x))> print>(>type>(s))> print>(>type>(y))> |
>
>
산출:
class 'int' class 'str' class 'list'>
예 2: 이름, 베이스 및 dict가 포함된 type()의 예
객체의 유형을 확인해야 하는 경우 Python을 사용하는 것이 좋습니다. isinstance() 함수 대신에. isinstance() 함수도 주어진 객체가 하위 클래스의 인스턴스인지 확인하기 때문입니다.
파이썬3
긴 문자열 자바
# Python code for type() with a name,> # bases and dict parameter> o1>=> type>(>'X'>, (>object>,),>dict>(a>=>'Foo'>, b>=>12>))> print>(>type>(o1))> print>(>vars>(o1))> class> test:> >a>=> 'Foo'> b>=> 12> o2>=> type>(>'Y'>, (test,),>dict>(a>=>'Foo'>, b>=>12>))> print>(>type>(o2))> print>(>vars>(o2))> |
>
>
산출:
{'b': 12, 'a': 'Foo', '__dict__': , '__doc__': None, '__weakref__': } {'b': 12, 'a': 'Foo', '__doc__': None}> Python에서 isinstance()는 무엇입니까?
isinstance() 함수는 객체(첫 번째 인수)가 클래스 정보 클래스(두 번째 인수)의 인스턴스 또는 하위 클래스인지 확인합니다.
isinstance() 함수의 구문
통사론: 인스턴스 (객체, 클래스 정보)
매개변수:
다중 테이블 SQL 선택
- object : 검사할 객체
- classinfo : 클래스, 유형 또는 클래스와 유형의 튜플
반품: 객체가 클래스의 인스턴스나 하위 클래스이면 true이고, 그렇지 않으면 false입니다.
클래스 정보가 유형 또는 유형의 튜플이 아닌 경우 TypeError 예외가 발생합니다.
예시 1:
이 예에서는 클래스 객체에 대한 isinstance() 테스트를 볼 수 있습니다.
파이썬3
# Python code for isinstance()> class> Test:> >a>=> 5> TestInstance>=> Test()> print>(>isinstance>(TestInstance, Test))> print>(>isinstance>(TestInstance, (>list>,>tuple>)))> print>(>isinstance>(TestInstance, (>list>,>tuple>, Test)))> |
>
>
산출:
True False True>
예시 2:
이 예에서는 정수, 부동 소수점 및 문자열 객체에 대한 테스트 isinstance()를 볼 수 있습니다.
파이썬3
weight>=> isinstance>(>17.9>,>float>)> print>(>'is a float:'>, weight)> num>=> isinstance>(>71>,>int>)> print>(>'is an integer:'>, num)> string>=> isinstance>(>'Geeksforgeeks'>,>str>)> print>(>'is a string:'>, string)> |
>
>
산출:
is a float: True is an integer: True is a string: True>
예시 3:
재스민 데이비스의 어린시절
이 예에서는 isinstance() 테스트를 볼 수 있습니다. 튜플 , 목록 , 사전 , 그리고 세트 물체.
파이썬3
tuple1>=> isinstance>((>'A'>,>'B'>,>'C'>),>tuple>)> print>(>'is a tuple:'>, tuple1)> set1>=> isinstance>({>'A'>,>'B'>,>'C'>},>set>)> print>(>'is a set:'>, set1)> list1>=> isinstance>([>'A'>,>'B'>,>'C'>],>list>)> print>(>'is a list:'>, list1)> dict1>=> isinstance>({>'A'>:>'1'>,>'B'>:>'2'>,>'C'>:>'3'>},>dict>)> print>(>'is a dict:'>, dict1)> |
>
>
CSS에서 이미지 중앙 정렬
산출:
is a tuple: True is a set: True is a list: True is a dict: True>
type()과 isinstance()의 차이점은 무엇입니까?
사람들이 저지르는 기본 오류 중 하나는 isinstance()가 더 적합한 type() 함수를 사용하는 것입니다.
- 객체가 특정 유형을 가지고 있는지 확인하는 경우 첫 번째 인수에 전달된 객체가 두 번째 인수에 전달된 유형 객체 중 하나인지 확인하기 위해 isinstance()를 사용하는 것이 좋습니다. 따라서 이는 모두 레거시 유형 객체 인스턴스를 갖는 서브클래싱 및 이전 스타일 클래스에서 예상대로 작동합니다.
- 반면에 type()은 단순히 객체의 유형 객체를 반환하고, 반환된 것을 다른 유형 객체와 비교하면 양쪽에서 정확히 동일한 유형 객체를 사용할 경우에만 True가 반환됩니다. Python에서는 객체의 유형을 검사하는 것보다 Duck Typing(유형 검사가 런타임에 연기되고 동적 유형 지정 또는 리플렉션을 통해 구현됨)을 사용하는 것이 더 좋습니다.
파이썬3
# Python code to illustrate duck typing> class> User(>object>):> >def> __init__(>self>, firstname):> >self>.firstname>=> firstname> >@property> >def> name(>self>):> >return> self>.firstname> class> Animal(>object>):> >pass> class> Fox(Animal):> >name>=> 'Fox'> class> Bear(Animal):> >name>=> 'Bear'> # Use the .name attribute (or property) regardless of the type> for> a>in> [User(>'Geeksforgeeks'>), Fox(), Bear()]:> >print>(a.name)> |
>
>
산출:
Geeksforgeeks Fox Bear>
- 사용하지 않는 다음 이유 type()은 상속 지원이 부족합니다. .
파이썬3
# python code to illustrate the lack of> # support for inheritance in type()> class> MyDict(>dict>):> >'''A normal dict, that is always created with an 'initial' key'''> >def> __init__(>self>):> >self>[>'initial'>]>=> 'some data'> d>=> MyDict()> print>(>type>(d)>=>=> dict>)> print>(>type>(d)>=>=> MyDict)> d>=> dict>()> print>(>type>(d)>=>=> dict>)> print>(>type>(d)>=>=> MyDict)> |
>
>
산출:
False True True False>
- MyDict 클래스에는 새로운 메서드 없이 사전의 모든 속성이 있습니다. 이는 사전과 똑같이 작동합니다. 그러나 type()은 예상된 결과를 반환하지 않습니다. isinstance()를 사용하는 것이 바람직합니다. 이 경우 예상된 결과를 제공하기 때문입니다.
파이썬3
데스크탑 ini가 뭐예요?
# python code to show isinstance() support> # inheritance> class> MyDict(>dict>):> >'''A normal dict, that is always created with an 'initial' key'''> >def> __init__(>self>):> >self>[>'initial'>]>=> 'some data'> d>=> MyDict()> print>(>isinstance>(d, MyDict))> print>(>isinstance>(d,>dict>))> d>=> dict>()> print>(>isinstance>(d, MyDict))> print>(>isinstance>(d,>dict>))> |
>
>
산출:
True True False True>