標籤: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說明