在项目中,我们会在每个接口验证客户端传过来的参数类型,如果验证不通过,返回给客户端“参数错误”错误码。
这样做不但便于调试,而且增加健壮性。因为客户端是可以作弊的,不要轻易相信客户端传过来的参数。
验证类型用type函数,非常好用,比如
>>type('foo') == str
True
立即学习“Python免费学习笔记(深入)”;
>>type(2.3) in (int,float)
True
立即学习“Python免费学习笔记(深入)”;
既然有了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 <type 'instance'>
old style class <type 'instance'>
new style class <class '__main__.C'>
True不存在说isinstance比type更好。只有哪个更适合需求。
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号