推荐使用 isinstance() 判断对象类型,因其支持继承和鸭子类型;慎用 type() 直接比较,因不识别子类且违背多态;泛化判断宜用 collections.abc 等抽象基类;type(obj).__name__ 仅用于调试展示。
在 Python 中判断对象类型,最常用且推荐的方式是使用 isinstance() 函数,而不是直接比较 type()。这是因为 isinstance() 支持继承关系,更符合 Python 的“鸭子类型”哲学,也更健壮。
它能正确识别子类实例,适用于大多数场景:
isinstance(obj, int) → 判断是否为整数(包括 bool,因为 bool 是 int 的子类)isinstance(obj, (str, bytes)) → 判断是否为字符串或字节串(支持元组传入多个类型)isinstance(obj, list) → 判断是否为列表isinstance(obj, MyClass)
type(obj) is int 或 type(obj) == list 虽然能工作,但不推荐,原因:
MyList 继承自 list,type(my_list) is list 返回 False
对容器、可迭代对象等,推荐用标准库的抽象基类(ABC),更语义化:
from collections.abc import Iterable → isinstance(obj, Iterable)
from collections.abc import Mapping → 判断是否为字典类结构(如 dict、defaultdict)from numbers import N
umber → 判断是否为任意数字类型(int、float、Decimal 等)仅用于日志、调试或展示,不用于逻辑判断:
type(obj).__name__ → 返回字符串,如 'str'、'datetime'
type(obj).__qualname__ → 对嵌套类更准确(如 'A.B')type(obj).__name__ == 'str' 不等于 isinstance(obj, str),尤其对第三方类型或别名不安全基本上就这些。日常开发中,优先用 isinstance();需要泛化判断容器行为时,用 collections.abc 中的抽象类;仅调试时才查 __name__。不复杂但容易忽略细节。