0
点赞
收藏
分享

微信扫一扫

Python语言学习讲解八:类型判断type与isinstance的区别






type和isinstance共同点:用于验证参数类型


在游戏项目中,我们会在每个接口验证客户端传过来的参数类型,如果验证不通过,返回给客户端“参数错误”错误码。

这样做不但便于调试,而且增加健壮性。因为客户端是可以作弊的,不要轻易相信客户端传过来的参数。

验证类型用type函数,非常好用,比如

>>type('foo') == str

True

>>type(2.3) in (int,float)

True

 


区别:在判断子类上。

type()不会认为子类是一种父类类型。

isinstance()会认为子类是一种父类类型。

eg:

[python] view plain copy


1. class Foo(object):  
2.     pass  
3. 
4. class Bar(Foo):  
5.     pass  
6. 
7. print type(Foo()) == Foo  
8. print type(Bar()) == Foo  
9. print isinstance(Bar(),Foo)


输出

True
False
True

 

需要注意的是,旧式类跟新式类的type()结果是不一样的。旧式类都是<type 'instance'>。

[python] view plain copy


1. class A:  
2.     pass  
3. 
4. class B:  
5.     pass  
6. 
7. class C(object):  
8.     pass  
9. 
10. print 'old style class',type(A())  
11. print 'old style class',type(B())  
12. print 'new style class',type(C())  
13. print type(A()) == type(B())


输出

old style class <type 'instance'>
old style class <type 'instance'>
new style class <class '__main__.C'>
True

 

不存在说isinstance比type更好。看情况使用

举报

相关推荐

0 条评论