Python isinstance 与 type 区别面试解析

7次阅读

Python isinstance 与 type 区别面试解析

isinstance 判断对象是否属于某类(含继承关系),type 只检查对象的直接类型,不认子类。面试常考这点,关键在“继承是否被认可”。

isinstance 支持继承判断

它会顺着 MRO(方法解析顺序)向上查找,只要对象是目标类或其任意子类的实例,就返回 True

  • class Animal: pass
  • class Dog(Animal): pass
  • d = Dog()
  • isinstance(d, Animal) → True(✅ 认子类)
  • isinstance(d, Dog) → True

type 只看“亲生爹妈”

type 返回对象的精确类型,比较时必须完全一致,不考虑继承链。

  • type(d) is Animal → False(❌ 不认父类
  • type(d) is Dog → True
  • type(d) == Animal → False(用 is 更安全,避免自定义 __eq__ 干扰)

实际使用建议

  • 做类型校验、函数参数判断时,优先用 isinstance —— 更符合面向对象直觉,也更健壮
  • 只有明确需要区分“是不是这个类本身”(比如禁止子类绕过限制),才用 type(obj) is SomeClass
  • 避免 type(obj) == SomeClass,既慢又可能出错;也不要用 type(obj) in [A, B],改用 isinstance(obj, (A, B))

一个易错点:内置类型 vs 类型对象

比如 type([])list,但 list 本身是 type 的实例(即元类实例)。面试若问“type(list) 是什么?”,答案是 type —— 因为类也是对象,它的类型是 type

立即学习Python免费学习笔记(深入)”;

text=ZqhQzanResources