Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python isinstance() Function

Python isinstance() Function

Python built-in function Python built-in function


Description

The isinstance() function determines whether an object is of a known type, similar to type().

Differences between isinstance() and type():

  • type() does not consider a subclass to be a type of its parent class; it does not take inheritance into account.

  • isinstance() considers a subclass to be a type of its parent class; it takes inheritance into account.

  • To determine whether two types are the same, isinstance() is recommended.

    Syntax

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

    
    isinstance(object, classinfo)
    

    Parameters

    Return Value

    Returns True if the object's type matches the type of the second parameter (classinfo), otherwise returns False.


    Example

    The following examples demonstrate the use of the isinstance function:

    a

    =

    2

    isinstance

    (

    a

    ,

    int

    )

    True

    isinstance

    (

    a

    ,

    str

    )

    False

    isinstance

    (

    a

    ,

    (

    str

    ,

    int

    ,

    list

    )

    )

    Returns True if it is one of the elements in the tuple

    True

    Difference between type() and 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

    Python built-in function Python built-in function