Home python Differences type () from isinstance ()

Differences type () from isinstance ()

Author

Date

Category

What is the difference between these two functions in Python ?


Answer 1, Authority 100%

Isinstance takes into account inheritance, and type – no.

Example:

Class Bacon:
  Pass
Class Spam (Bacon):
  Pass
x = spam ()
TYPE (X) IS SPAM # TRUE
Type (X) Is Bacon # False
IsInstance (X, SPAM) # true
Isinstance (X, Bacon) # true


In practice, this feature can be used to support polymorphism.

Suppose that the function must change behavior depending on the type of transmitted data. For example, according to a special processing of dictionaries:

def f (arg):
  IF Type (ARG) is DICT:
    Print ('Promed dictionary!')

If you pass the usual dictionary in it, everything will be fine. But if you pass Collections.OrderedDict Everything will break, despite the fact that OrderedDict supports all the necessary methods.

To avoid this and process all types that are inherited from DICT , you can use Isinstance :

if isinstance (arg, dict):
  Print ('Promed dictionary!')

Answer 2

Although the type () function returns the type of transmitted argument, it can be checked if an argument belongs to some kind of type:

a = 10
B = [1,2,3]
Type (a) == int #true
Type (B) == List #true
Type (a) == Float #False

Unlike Type () , the isinstance () function>is specifically created to check the data accessories to a specific class (data type):

isinstance (a, int) #true
Isinstance (B, List) #true
Isinstance (B, Tuple) #false
C = (4,5,6)
Isinstance (C, Tuple) #true

In addition, isinstance () Compared to Type () allows you to check this to affiliate at least one type from the tavern passed as the second argument:

isinstance (a, (Float, Int, Str)) #true
IsInstance (A, List, Tuple, Dict)) #false

Another difference Isinstance () . This feature supports inheritance. For Isinstance () , an instance of a derived class is also an instance of the base class. For Type () it is not:

class a (list):
  Pass
a = a ()
Type (a) == List #False
Type (a) == A #TRUE
IsInstance (A, A) #TRUE
Isinstance (A, List) #true

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions