美文网首页
为什么不推荐使用 type

为什么不推荐使用 type

作者: 智勇双全的小六 | 来源:发表于2018-04-11 20:00 被阅读0次

因为 type 不能判断 subclass

class A:
  pass

class B(A):
  pass

a = A()
b = B()

使用 type(a), 返回的是 <class 'A'>
使用 type(B()),返回的是<class 'B'>
当我们判断类型是为了查看 b 是不是有某些方法时,这样写会返回 False

type(b) == A
// False
isinstance(b,A) 
// True

相关文章

网友评论

      本文标题:为什么不推荐使用 type

      本文链接:https://www.haomeiwen.com/subject/ajwzhftx.html