Python內建函數(34)——isinstance

來源:互聯網
上載者:User

標籤:util   參數   virtual   utils   scn   需要   mod   對象   cts   

英文文檔:

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

 

Python內建函數(34)——isinstance

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.