python中isinstance的用法

來源:互聯網
上載者:User

Isinstance(

object, classinfo)

Return true if the
object argument is an instance of the
classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if
classinfo is a type object and
object is an object of that type. If
object is not a class instance or an object of the given type, the function always returns false. If
classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence
types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a
TypeError exception is raised.
Changed in version 2.2: Support for a tuple of type information was added.

isinstance說明如下:

其第一個參數為對象,第二個為類型名或類型名的一個列表。其傳回值為布爾型。若對象的類型與參數二的類型相同則返回True。若參數二為一個元組,則若物件類型與元組中類型名之一相同即返回True。

執行個體:

Python可以得到一個對象的類型 ,利用type函數:

>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>
以利用isinstance函數,來判斷一個對象是否是一個已知的類型。

>>>isinstance(lst, list)
Trueisinstance(lst, (int, str, list))
True

>>> isinstance('iioo',(str))  
true

>>> isinstance(32434,(int))    
true

>>> isinstance('safasdf',(int,long))  
false

用cmp來比較整數的大小

>>> cmp(3,2)      
1

>>> cmp(20,30)   
-1

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.