溫馨提示×

python中instance函數(shù)的應(yīng)用案例

小樊
86
2024-09-06 15:16:22
欄目: 編程語言

在Python中,isinstance()函數(shù)用于檢查一個(gè)對象是否為特定類的實(shí)例。這個(gè)函數(shù)非常有用,因?yàn)樗试S你在運(yùn)行時(shí)檢查對象的類型,并根據(jù)需要進(jìn)行相應(yīng)的操作。以下是一些使用isinstance()函數(shù)的應(yīng)用案例:

  1. 檢查輸入?yún)?shù)的類型:
def add_numbers(a, b):
    if not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
        raise TypeError("Both arguments must be numbers")
    return a + b

result = add_numbers(3, 4)
print(result)  # 輸出:7

result = add_numbers(3.5, 4)
print(result)  # 輸出:7.5

result = add_numbers("3", 4)  # 將拋出TypeError,因?yàn)?quot;3"不是一個(gè)數(shù)字
  1. 根據(jù)對象類型執(zhí)行不同操作:
def process_data(data):
    if isinstance(data, list):
        return [x * 2 for x in data]
    elif isinstance(data, dict):
        return {k: v * 2 for k, v in data.items()}
    else:
        raise TypeError("Unsupported data type")

result = process_data([1, 2, 3])
print(result)  # 輸出:[2, 4, 6]

result = process_data({"a": 1, "b": 2})
print(result)  # 輸出:{"a": 2, "b": 4}

result = process_data("not supported")  # 將拋出TypeError,因?yàn)樽址皇侵С值臄?shù)據(jù)類型
  1. 自定義類型檢查:
class MyClass:
    pass

def custom_type_check(obj):
    if isinstance(obj, MyClass):
        print("The object is an instance of MyClass")
    else:
        print("The object is not an instance of MyClass")

my_obj = MyClass()
custom_type_check(my_obj)  # 輸出:"The object is an instance of MyClass"

custom_type_check("not my class")  # 輸出:"The object is not an instance of MyClass"

這些示例展示了如何使用isinstance()函數(shù)在不同場景中檢查對象的類型,并根據(jù)需要執(zhí)行相應(yīng)的操作。

0