Python isinstance() 메서드

Python isinstance() 함수 객체가 지정된 유형이면 True를 반환하고, 일치하지 않으면 False를 반환합니다. 이 기사에서는 Python에서 isinstance() 메서드가 어떻게 작동하는지 살펴보겠습니다.

  Input:   isinstance([1, 2, 3], list)   Output:   True   Explanation:   The first parameter passed is of list type.   Input:   isinstance(10, str)   Output:   False   Explanation:   The first parameter, 10 is an integer and not a string. 

Python isinstance() 함수 구문

isinstance() 메소드는 파이썬 다음과 같은 구문이 있습니다.

통사론:

isinstance(obj, 클래스)

매개변수:

  • 객체 : 클래스의 일부로 확인해야 하는 개체입니다.
  • 수업 : 객체를 확인해야 하는 클래스 또는 유형의 클래스/유형/튜플입니다.

반품 : True, 단일 클래스가 전달되면 객체가 지정된 클래스/유형에 속하고, 클래스/유형의 튜플이 전달되면 클래스/유형 중 하나에 속하고, 그렇지 않으면 False를 반환합니다.

유형오류: 언급된 유효한 클래스 유형 이외의 것이 있는 경우.

Python에서 인스턴스() 함수는 어떻게 작동합니까?

Python에서 인스턴스() 메서드는 비교 연산자처럼 작동합니다. 두 개의 인수가 필요합니다. 하나는 Python 객체이고 다른 하나는 클래스 유형입니다. 객체를 지정된 유형의 클래스 또는 하위 클래스와 비교하고 부울 값(True 또는 False)을 반환합니다.

파이썬3




numbers> => [> 1> ,> 2> ,> 3> ,> 4> ,> 2> ,> 5> ]> # Check if 'numbers' is an instance of a list> result> => isinstance> (numbers,> list> )> if> result:> > print> (> 'The variable 'numbers' is an instance of a list.'> )> else> :> > print> (> 'The variable 'numbers' is not an instance of a list.'> )>

산출

The variable 'numbers' is an instance of a list. 

Python의 isinstance() 메서드 예

우리는 단일 클래스 유형을 제공하거나 파이썬 튜플 인스턴스() 메소드에 대한 클래스입니다. 튜플의 경우, 인스턴스() 메소드는 튜플의 모든 요소를 ​​확인하고 객체가 튜플 요소 중 하나의 인스턴스이면 True를 반환하고, 그렇지 않으면 False를 반환합니다. Python 인스턴스() 메서드의 몇 가지 예를 살펴보겠습니다.

Int 및 List가 있는 Python isinstance

이 예에서는 isinstance() 메소드가 Integer 데이터 유형 및 파이썬 목록 . 정수와 목록이 정수 또는 문자열 유형의 인스턴스인지 확인합니다.

파이썬3




# initializing native types> test_int> => 5> test_list> => [> 1> ,> 2> ,> 3> ]> # testing with isinstance> print> (> 'Is test_int integer? : '> +> str> (> isinstance> (test_int,> int> )))> print> (> 'Is test_int string? : '> +> str> (> isinstance> (test_int,> str> )))> print> (> 'Is test_list integer? : '> +> str> (> isinstance> (test_list,> int> )))> print> (> 'Is test_list list? : '> +> str> (> isinstance> (test_list,> list> )))> # testing with tuple> print> (> 'Is test_int integer or list or string? : '> > +> str> (> isinstance> (test_int, (> int> ,> list> ,> str> ))))>

산출

Is test_int integer? : True Is test_int string? : False Is test_list integer? : False Is test_list list? : True Is test_int integer or list or string? : True 

객체와 함께 isinstance() 사용 시연

이 예에서는 Python에서 객체의 클래스를 확인합니다. 즉, 객체가 클래스의 인스턴스인지 파생 클래스인지 확인합니다.

파이썬3




# declaring classes> class> gfg1:> > a> => 10> # inherited class> class> gfg2(gfg1):> > string> => 'techcodeview.com'> # initializing objects> obj1> => gfg1()> obj2> => gfg2()> # checking instances> print> (> 'Is obj1 instance of gfg1? : '> +> str> (> isinstance> (obj1, gfg1)))> print> (> 'Is obj2 instance of gfg2? : '> +> str> (> isinstance> (obj2, gfg2)))> print> (> 'Is obj1 instance of gfg2? : '> +> str> (> isinstance> (obj1, gfg2)))> # check inheritance case> # return true> print> (> 'Is obj2 instance of gfg1? : '> +> str> (> isinstance> (obj2, gfg1)))>

산출

Is obj1 instance of gfg1? : True Is obj2 instance of gfg2? : True Is obj1 instance of gfg2? : False Is obj2 instance of gfg1? : True 

문자열이 있는 Python isinstance()

이 예에서는 isinstance() 함수를 파이썬 문자열 Python에서 객체의 클래스를 확인합니다.

파이썬3




test_str> => 'techcodeview.com'> print> (> 'Is test_str string? : '> +> str> (> isinstance> (test_str,> str> )))>

산출

Is test_str string? : True 

사전이 있는 Python isinstance()

Python isinstance() 메서드는 다음과도 작동합니다. 사전 Python에서 개체를 검색하고 개체의 클래스를 확인합니다.

파이썬3




test_dict> => {> 'apple'> :> 1> ,> 'Ball'> :> 2> }> print> (> 'Is test_str dictionary? : '> +> str> (> isinstance> (test_dict,> dict> )))>

산출

Is test_str dictionary? : True 

클래스 메소드를 사용하는 Python isinstance

이 예제에서는 isinstance() 메서드를 사용하여 지정된 유형의 클래스 함수에서 반환된 값을 확인하고 Python에서 객체의 클래스를 확인합니다.

파이썬3




class> geeks:> > course> => 'DSA'> > > def> purchase(obj):> > return> obj.course> > > geeks.purchase> => classmethod> (geeks.purchase)> str> (> isinstance> (geeks.purchase(),> str> ))>

산출

True 

Python의 isinstance()와 type() 메서드의 차이점

다음 표에서는 isinstance() 메서드와 isinstance() 메서드 간의 차이점을 보여줍니다. 유형() 파이썬의 메소드.

isinstance()

유형()

구문: isinstance(객체, 클래스) 구문: 유형(객체)

객체가 특정 클래스 유형인지 확인합니다.

객체의 클래스 유형을 반환합니다.

객체가 클래스와 그 하위 클래스에 속하는지 확인할 수 있습니다.

상속을 다룰 수는 없습니다

type()에 비해 속도가 빠릅니다. isinstance()보다 느립니다.
True 또는 False를 반환합니다. 객체의 유형을 반환합니다.
한 번에 여러 클래스를 확인할 수 있습니다. 이렇게 할 수는 없습니다
예: isinstance(10, (int, str)) 예: 종류(10)