python类型比较的3种方式
2015-07-20 23:09
591 查看
通过types模块的类成员来判断,其实所有python中的类型都是这个types模块中类型的实例。
import types
type(x) is types.IntType # 判断是否int 类型
type(x) is types.StringType #是否string类型
type(x) is types.InstanceType #是否是自定义的实例对象, isinstance函数不支持比较这个
通过已知类型比较,因为python中所有相同类型的对象他们所引用的类型都是同一个,所以可以通过如下的方式对比:
type(x) == types(1) # 判断是否int 类型
type(x) == type('a') #是否string类型
type(x) is types(1) # 判断是否int 类型
type(x) is type('a') #是否string类型
使用内建isinstance函数:
Python可以得到一个对象的类型 ,利用type函数:
>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>
同样可以利用isinstance函数,来判断一个对象是否是一个已知的类型。其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组, 则若对象类型与元组中类型名之一相同即返回True。
>>>isinstance(lst, list)
True
>>>isinstance(lst, (int, str, list))
True
import types
type(x) is types.IntType # 判断是否int 类型
type(x) is types.StringType #是否string类型
type(x) is types.InstanceType #是否是自定义的实例对象, isinstance函数不支持比较这个
通过已知类型比较,因为python中所有相同类型的对象他们所引用的类型都是同一个,所以可以通过如下的方式对比:
type(x) == types(1) # 判断是否int 类型
type(x) == type('a') #是否string类型
type(x) is types(1) # 判断是否int 类型
type(x) is type('a') #是否string类型
使用内建isinstance函数:
Python可以得到一个对象的类型 ,利用type函数:
>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>
同样可以利用isinstance函数,来判断一个对象是否是一个已知的类型。其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组, 则若对象类型与元组中类型名之一相同即返回True。
>>>isinstance(lst, list)
True
>>>isinstance(lst, (int, str, list))
True
相关文章推荐
- Python filter()函数的用法
- Python reduce()函数的用法
- 【Python 学习手册笔记】Python 语句简介
- Python进阶---一Python小测试
- python测试框架nose研究
- Python进阶---目录名的拼接
- python+M2Crypto+windows安装
- 机器学习算法与Python实践之(三)支持向量机(SVM)进阶
- python百度贴吧爬虫,以及爬虫简要入门
- Python科学计算的瑞士军刀——Anaconda 安装与配置
- 交互模式下python自动补全
- [转]0.python:scikit-learn基本用法
- 在Python中怎么表达True
- [转]Python机器学习工具箱
- Python的高级特性6:使用__slots__真的能省很多内存
- Python: zip()的使用
- Python内存管理
- java调用python(jython)的报错
- python程序报"iccp known incorrect srgb profile" 警告
- python模块:调用系统命令模块subprocess等