在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 = 42check_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_的实例。根据检查结果,我们打印相应的消息。


