当前位置:
首页 > Python基础教程 >
-
python数据类型判断type与isinstance的区别
在项目中,我们会在每个接口验证客户端传过来的参数类型,如果验证不通过,返回给客户端“参数错误”错误码。
这样做不但便于调试,而且增加健壮性。因为客户端是可以作弊的,不要轻易相信客户端传过来的参数。
验证类型用type函数,非常好用,比如
>>type('foo') == str
True
>>type(2.3) in (int,float)
True
既然有了type()来判断类型,为什么还有isinstance()呢?
一个明显的区别是在判断子类。
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
千言不如一码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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()结果是不一样的。旧式类都是<type 'instance'>。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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 |
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式