溫馨提示×

python中instance函數(shù)的類型檢查

小樊
83
2024-09-06 15:41:36
欄目: 編程語言

在Python中,isinstance()是一個內(nèi)置函數(shù),用于檢查對象是否為指定類型。它接受兩個參數(shù):要檢查的對象和要比較的類型。如果對象是指定類型的實例,則返回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的函數(shù),該函數(shù)接受兩個參數(shù):要檢查的對象obj和要比較的類型type_。然后,我們使用isinstance()函數(shù)檢查obj是否為type_的實例。根據(jù)檢查結(jié)果,我們打印相應(yīng)的消息。

0