英文文檔:
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 false. If classinfo is a tuple of type 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 is raised.
說明:
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