在Python中,isinstance()是一個內置函數,用于檢查對象是否為指定類型。它接受兩個參數:要檢查的對象和要比較的類型。如果對象是指定類型的實例,則返回True,否則返回False。
以下是使用isinstance()進行類型檢查的示例:
def check_type(obj, type_):
if isinstance(obj, type_):
print("The object is an instance of the specified type.")
else:
print("The object is not an instance of the specified type.")
# 示例
num = 42
check_type(num, int) # 輸出 "The object is an instance of the specified type."
str_ = "Hello, world!"
check_type(str_, str) # 輸出 "The object is an instance of the specified type."
lst = [1, 2, 3]
check_type(lst, list) # 輸出 "The object is an instance of the specified type."
check_type(lst, tuple) # 輸出 "The object is not an instance of the specified type."
在這個示例中,我們定義了一個名為check_type的函數,該函數接受兩個參數:要檢查的對象obj和要比較的類型type_。然后,我們使用isinstance()函數檢查obj是否為type_的實例。根據檢查結果,我們打印相應的消息。