[Python daily use] isinstance() function in python

grammar

isinstance(object, classinfo)

Function definition

def isinstance(x, A_tuple): # real signature unknown; restored from __doc__
    """
    Return whether an object is an instance of a class or of a subclass thereof.
    
    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.
    """
    pass

To put it simply, the isinstance() function determines whether an object is a known type, similar to type().
But it is different from type:

  • type() does not consider the subclass to be a parent type, and does not consider the inheritance relationship.
  • isinstance() will consider the subclass to be a parent class type, and consider the inheritance relationship.
    The classinfo here can be for ordinary types
  • int,
  • float,
  • bool,
  • complex,
  • str (string),
  • list,
  • dict (dictionary),
  • set,
  • tuple

Example

isinstance(2,int)

Guess you like

Origin blog.csdn.net/weixin_51656605/article/details/112982950