如何在 Python 中检查数据类型(type 与 isinstance)

了解如何在 Python 中检查数据类型。了解何时使用 type() 与 isinstance()、处理自定义类以及编写安全类型检查验证。

在编辑器中尝试此解决方案

概述

Python 是一种动态类型语言,这意味着变量可以保存任何数据类型的值,并且它们的类型可以在执行过程中更改。虽然这种灵活性可以加快初始开发速度,但它还要求您在运行特定于类型的操作(例如对整数执行算术或调用字符串方法)之前在运行时验证变量类型。

为了检查对象的数据类型,Python 提供了两个主要函数:“type()”和“isinstance()”。 `type(obj)` 函数返回对象的精确类类型。虽然您可以使用 type(obj) == int 来验证数字是否为整数,但通常不鼓励使用此方法,因为它不支持继承结构(整数的子类将计算为 False)。

推荐的检查类型的 Python 方法是“isinstance(obj, class_info)”。此函数检查对象是否是指定类或从该类继承的任何子类的实例。它还支持检查类元组(例如,“isinstance(value, (int, float))”),使验证代码高度灵活和健壮。

代码和执行输出

此脚本演示了使用 type() 和 isinstance() 检查变量类型,显示继承方面的差异。

value_int = 42
value_str = "hello"

# 1. Checking type using isinstance() (Recommended)
is_number = isinstance(value_int, int)
print(f"Is {value_int} an int? {is_number}")

# Checking against multiple possible types
is_num_or_str = isinstance(value_str, (int, float, str))
print(f"Is '{value_str}' int, float, or str? {is_num_or_str}")

# 2. Checking type using type() (For exact class matches)
print(f"Exact type of value_int: {type(value_int).__name__}")
print("Is value_int exactly an int?", type(value_int) is int)

# 3. Inheritance difference
class CustomList(list):
    pass

my_list = CustomList([1, 2, 3])

print("\nInheritance testing:")
print("isinstance(my_list, list):", isinstance(my_list, list))
print("type(my_list) is list:", type(my_list) is list)
端子输出
Is 42 an int? True
Is 'hello' int, float, or str? True
Exact type of value_int: int
Is value_int exactly an int? True

Inheritance testing:
isinstance(my_list, list): True
type(my_list) is list: False

逐步实施

  • 使用 isinstance(variable, type_name) 进行一般类型检查(符合继承)。
  • 传递 isinstance(variable, (int, float)) 等类型的元组来检查多个类。
  • 仅当必须保证类的精确匹配而忽略子类时,才使用 type(variable) is type_name 。

常见问题解答

为什么 isinstance() 优于 type()?

isinstance() 支持对象继承和多态性。如果您对内置类型进行子类化,isinstance() 将正确地将其识别为父类的实例,而 type() 将计算为 False。

如何检查对象是否可调用(如函数)?

使用内置的 callable() 函数,如果对象可以像函数一样调用,则该函数返回 True。

相关主题

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。