首頁  >  文章  >  後端開發  >  Python內建isinstance函數詳細介紹

Python內建isinstance函數詳細介紹

高洛峰
高洛峰原創
2017-03-21 09:32:201982瀏覽

英文文件:

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns fse . objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError ##exception#. ##說明:

  1.

函數

功能用於判斷對像是否為類型對象的實例,object參數表示需要檢查的對象,calssinfo參數表示類型對象。

  2. 如果object參數是classinfo類型物件(或classinfo類別物件的直接、間接、虛擬子類別)的實例,則傳回True。

>>> isinstance(1,int)
True
>>> isinstance(1,str)
False

# 定义3各类:C继承B,B继承A
>>> class A:
    pass

>>> class B(A):
    pass

>>> class C(B):
    pass

>>> a = A()
>>> b = B()
>>> c = C()
>>> isinstance(a,A) #直接实例
True
>>> isinstance(a,B)
False
>>> isinstance(b,A) #子类实例 
True
>>> isinstance(c,A) #孙子类实例
True

  3. 如果object參數傳入的是類型對象,則一律傳回False。

>>> isinstance(str,str)
False 
>>> isinstance(bool,int)
False

  4. 如果classinfo類型對象,是多個類型對象組成的元組,如果

object對象

是元組的任一類型對像中實例,則傳回True,否則傳回False。

>>> isinstance(a,(B,C))
False
>>> isinstance(a,(A,B,C))
True
  5. 如果classinfo類型對象,不是一個類型對像或由多個型別對象組成的元組,則會報錯(TypeError)。
>>> isinstance(a,[A,B,C])
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    isinstance(a,[A,B,C])
TypeError: isinstance() arg 2 must be a type or tuple of types

以上是Python內建isinstance函數詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn