內建函式isinstance說明

來源:互聯網
上載者:User

標籤:ar   os   for   on   資料   bs   ad   ef   as   

 isinstance說明如下:  isinstance(object, class-or-type-or-tuple) -> bool    Return whether an object is an instance of a class or of a subclass thereof.  With a type as second argument, return whether that is the object‘s type.  The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A)  or isinstance(x, B) or ... (etc.).
其第一個參數為對象,第二個為類型名或類型名的一個列表。其傳回值為布爾型。若對象的類型與參數二的類型相同則返回True。若參數二為一個元組,則若物件類型與元組中類型名之一相同即返回True。
 
 
 

傳入了不恰當的參數時,內建函數abs會檢查出參數錯誤,而我們定義的my_abs沒有參數檢查,所以,這個函數定義不夠完善。

讓我們修改一下my_abs的定義,對參數類型做檢查,只允許整數和浮點數類型的參數。資料類型檢查可以用內建函數isinstance實現:

def my_abs(x):    if not isinstance(x, (int, float)):        raise TypeError(‘bad operand type‘)    if x >= 0:        return x    else:        return -x

添加了參數檢查後,如果傳入錯誤的參數類型,函數就可以拋出一個錯誤:

>>> my_abs(‘A‘)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 3, in my_absTypeError: bad operand type

內建函式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.