The Python isinstance() function

Python isinstance() function

describes the

isinstance() function to determine if an object is a known type, similar to type().

isinstance() differs from type():

  • type() does not consider a subclass to be a parent class, regardless of inheritance.

  • isinstance() will consider a subclass to be a parent class, considering inheritance.

If you want to determine if the two types are the same, it is recommended to use isinstance().

语法

The following is the syntax of the isinstance() method:

isinstance(object, classinfo)

parameter

  • object -- instance object.
  • classinfo -- can be direct or indirect class names, basic types, or tuples composed of them.

回值

Returns True if the type of the object is the same as the type of the parameter 2 (classinfo), otherwise returns False. .

Instance

The following shows an example of using the isinstance function:

>>>a = 2 >>> isinstance (a, int) True >>> isinstance (a,str) False >> > isinstance (a,(str,int,list)) # is one of the tuples that returns True True

type() differs from isinstance():

class A: pass class B(A): pass isinstance(A(), A) # returns True type(A()) == A # returns True isinstance(B(), A) # returns True type(B()) == A # returns False

1 Notes

  1.    ppjyy

      jko***[email protected]

    for basic types For classinfo can be:

    int,float,bool,complex,str(字符串),list,dict(字典),set,tuple

    It should be noted that the string of classinfo is str instead of string, the dictionary is also abbreviated dict

    instance

    arg=123
    isinstance(arg, int)    #输出True
    isinstance(arg, str)    #输出False
    isinstance(arg, string) #报错