Metoda isinstance() w Pythonie

Funkcja isinstance() w Pythonie zwraca True, jeśli obiekt jest określonego typu, a jeśli nie pasuje, zwraca False. W tym artykule zobaczymy jak metoda isinstance() działa w Pythonie

Przykład

  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. 

Składnia funkcji isinstance() w Pythonie

Metoda isinstance() w Pyton ma następującą składnię:

Składnia:

isinstance(obj, klasa)

Parametry:

  • obj: Obiekt, który należy sprawdzić w ramach zajęć, czy nie.
  • klasa : klasa/typ/krotka klasy lub typu, względem którego należy sprawdzić obiekt.

Zwroty : Prawda, jeśli obiekt należy do danej klasy/typu w przypadku przekazania pojedynczej klasy lub dowolnej klasy/typu w przypadku przekazania krotki klasy/typu, w przeciwnym razie zwraca False.

TypBłąd: jeśli cokolwiek innego niż wymieniony prawidłowy typ klasy.

Jak funkcja instancji() działa w Pythonie?

W Pythonie metoda instancji() działa jak operator porównania. Pobiera dwa argumenty, jeden jest obiektem Pythona, a drugi jest typem klasy. Porównuje obiekt z określonym typem klasy lub podklasy i zwraca wartość logiczną, czyli True lub False.

Python3




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.'> )>

Wyjście

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

Przykłady metody isinstance() w Pythonie

Możemy zapewnić pojedynczy typ klasy lub a Krotka Pythona klas do metody instancji(). W przypadku krotki metoda instancja() sprawdza wszystkie elementy w krotce i zwraca True, jeśli obiekt jest instancją któregokolwiek z elementów krotki, w przeciwnym razie zwraca False. Zobaczmy kilka przykładów metody Pythona instancji().

Python jest instancją z Int i List

W tym przykładzie zobaczymy, jak metoda isinstance() działa z typem danych Integer i Lista Pythona . Sprawdzamy, czy liczba całkowita i lista są instancjami typu Integer czy String.

Python3




# 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> ))))>

Wyjście

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 

Demonstracja użycia isinstance() z obiektami

W tym przykładzie sprawdzimy klasę obiektu w Pythonie, tj. czy obiekt jest instancją klasy lub jej klasą pochodną.

Python3




# 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)))>

Wyjście

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() z ciągiem

W tym przykładzie użyjemy funkcji isinstance() z a Ciąg Pythona i sprawdź klasę obiektu w Pythonie.

Python3




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

Wyjście

Is test_str string? : True 

Python isinstance() ze słownikiem

Metoda isinstance() w Pythonie działa również z słownik object i sprawdź klasę obiektu w Pythonie.

Python3




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

Wyjście

Is test_str dictionary? : True 

Python jest instancją z metodami klasowymi

W tym przykładzie używamy metody isinstance() do sprawdzenia wartości zwracanej przez funkcję klasy o określonym typie oraz do sprawdzenia klasy obiektu w Pythonie.

Python3




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

Wyjście

True 

Różnica między metodami isinstance() i type() w Pythonie

W poniższej tabeli przedstawiono różnice między metodą isinstance() a metodą typ() metoda w Pythonie.

isinstancja()

typ()

Składnia: isinstance(obiekt, klasa) Składnia: typ (obiekt)

Sprawdza, czy obiekt należy do określonego typu klasy

Zwraca typ klasy obiektu

Może sprawdzić, czy obiekt należy do klasy i jej podklas

Nie może zajmować się dziedziczeniem

Jest szybszy w porównaniu do type() Jest wolniejszy niż isinstance()
Zwraca wartość True lub False Zwraca typ obiektu
Może sprawdzać wiele klas jednocześnie Nie może tego zrobić
Przykład: isinstance(10, (int, str)) Przykład: typ(10)