您好,欢迎访问一九零五行业门户网

python数据类型判断type与isinstance的区别

在项目中,我们会在每个接口验证客户端传过来的参数类型,如果验证不通过,返回给客户端“参数错误”错误码。
这样做不但便于调试,而且增加健壮性。因为客户端是可以作弊的,不要轻易相信客户端传过来的参数。
验证类型用type函数,非常好用,比如
>>type('foo') == str
true
>>type(2.3) in (int,float)
true
既然有了type()来判断类型,为什么还有isinstance()呢?
一个明显的区别是在判断子类。
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
千言不如一码。
class foo(object): pass class bar(foo): pass print type(foo()) == foo print type(bar()) == foo print isinstance(bar(),foo) class foo(object): pass class bar(foo): pass print type(foo()) == foo print type(bar()) == foo print isinstance(bar(),foo) 输出 true false true
需要注意的是,旧式类跟新式类的type()结果是不一样的。旧式类都是。
class a: pass class b: pass class c(object): pass print 'old style class',type(a()) print 'old style class',type(b()) print 'new style class',type(c()) print type(a()) == type(b()) class a: pass class b: pass class c(object): pass print 'old style class',type(a()) print 'old style class',type(b()) print 'new style class',type(c()) print type(a()) == type(b()) 输出 old style class old style class new style class true
不存在说isinstance比type更好。只有哪个更适合需求。
其它类似信息

推荐信息