在Python中,isinstance()
函数用于检查一个对象是否为特定类的实例。这个函数非常有用,因为它允许你在运行时检查对象的类型,并根据需要进行相应的操作。以下是一些使用isinstance()
函数的应用案例:
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,因为"3"不是一个数字
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,因为字符串不是支持的数据类型
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()
函数在不同场景中检查对象的类型,并根据需要执行相应的操作。