您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 内江分类信息网,免费分类信息发布

python数据类型判断

2023/1/3 22:30:48发布41次查看
python判断变量数据类型时,建议使用isinstance()方法代替type(). 进行类型检查首先想到的就是用type(),但是type在某些特定情况下判断类型存在问题,今天就来说下type在python类型判断时可能出现的问题。
type()方法
例子: int类型判断
types.booleantype # bool类型
types.buffertype # buffer类型
types.builtinfunctiontype # 内建函数,比如len()
types.builtinmethodtype # 内建方法,指的是类中的方法
types.classtype # 类类型
types.codetype # 代码块类型
types.complextype # 复数类型
types.dictproxytype # 字典代理类型
types.dicttype # 字典类型
types.dictionarytype # 字典备用的类型
types.ellipsistype
types.filetype # 文件类型
types.floattype # 浮点类型
types.frametype
types.functiontype # 函数类型
types.generatortype
types.getsetdescriptortype
types.instancetype # 实例类型
types.inttype # int类型
types.lambdatype # lambda类型
types.listtype # 列表类型
types.longtype # long类型
types.memberdescriptortype
types.methodtype # 方法类型
types.moduletype # module类型
types.nonetype # none类型
types.notimplementedtype
types.objecttype # object类型
types.slicetypeh
types.stringtype # 字符串类型
types.stringtypes
types.tracebacktype
types.tupletype # 元组类型
types.typetype # 类型本身
types.unboundmethodtype
types.unicodetype
types.xrangetype
isinstance方法
isinstance(object, classinfo)
object表示实例,classinfo可以是直接或间接类名、基本类型或者有它们组成的元组。
那为什么不推荐使用type进行类型检查呢?
看下面的代码:
上面代码输出false
这就说明i和n的类型是不一样的,而实际上userint是继承自int的,所以这个判断是存在问题的,当我们对python内建类型进行扩展的时候,type返回的结果就不够准确了。我们再看一个例子:
这段代码输出的是true
type比较的结果a和b的类型是一样的,结果明显是不准确的。在old-style class中,任意instance的type都是'instance'。所以绝对不能用type来判断其类型。
另外这个问题又与python的思想有关,正常情况下不应该编写代码检查类型的,而应该直接假设被操作的instance具有你希望的属性,否则抛出异常。即使需要检查类型,也应该用isinstance来判断,这样你期望类型的subclass也能正常被处理(比如,一个函数需要处理message类型,那么它应该也能处理message的子类型mymessage,所以应该使用isinstance(arg,message)这样来判断而不是type(arg) == message来判断)
结论:
尽量不要使用type()方法,多使用isinstance(),这样可以减少错误。
内江分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录