永发信息网

Python中为什么推荐使用isinstance来进行类型判断

答案:2  悬赏:60  手机版
解决时间 2021-03-07 06:59
  • 提问者网友:半生酒醒
  • 2021-03-06 08:09
Python中为什么推荐使用isinstance来进行类型判断
最佳答案
  • 五星知识达人网友:拜訪者
  • 2021-03-06 08:48
因为2.x跟3.x里type( )返回几个不一样,
2.x中type( )的返回类型对象是赋给该类型的另一个对象的对象。在3.x中则直接返回类。
而isinstance则没有这样的区别。
而其实,在代码中检验了特定的类型,会破坏它的灵活性,限制它只能使用一种类型的工作。
全部回答
  • 1楼网友:千杯敬自由
  • 2021-03-06 09:46
python在定义变量的时候不用指明具体的的类型,解释器会在运行的时候会自动检查 变量的类型,并根据需要进行隐式的类型转化。因为python是动态语言,所以一般情 况下是不推荐进行类型转化的。比如"+"操作时,如果加号两边是数据就进行加法操 作,如果两边是字符串就进行字符串连接操作,如果两边是列表就进行合并操作,甚 至可以进行复数的运算。解释器会在运行时根据两边的变量的类型调用不同的内部方法。 当加号两边的变量类型不一样的时候,又不能进行类型转化,就会抛出typeerror的异常。 但是在实际的开发中,为了提高代码的健壮性,我们还是需要进行类型检查的。而进行 类型检查首先想到的就是用type(),比如使用type判断一个int类型。 import types if type(1) is types.integer: print('1是int类型') else: print('1不是int类型') 上面的程序会输出:1是int类型 我们在types中可以找到一些常用的类型,在2.7.6中显示的结果: 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 在python 3中,类型已经明显减少了很多 types.builtinfunctiontype types.builtinmethodtype types.codetype types.dynamicclassattribute types.frametype types.functiontype types.generatortype types.getsetdescriptortype types.lambdatype types.mappingproxytype types.memberdescriptortype types.methodtype types.moduletype types.simplenamespace types.tracebacktype types.new_class types.prepare_class 但是我们并不推荐使用type来进行类型检查,之所以把这些类型列出来,也是为了扩展知识 面。那为什么不推荐使用type进行类型检查呢?我们来看一下下面的例子。 import types class userint(int): def __init__(self, val=0): self.val = int(val) i = 1 n = userint(2) print(type(i) is type(n)) 上面的代码输出:false 这就说明i和n的类型是不一样的,而实际上userint是继承自int的,所以这个判断是存在问题的, 当我们对python内建类型进行扩展的时候,type返回的结果就不够准确了。我们再看一个例子。 class a(): pass class b(): pass a = a() b = b() print(type(a) is type(b)) 代码的输出结果: true type比较的结果a和b的类型是一样的,结果明显是不准确的。这种古典类的实例,type返回的结果都 是一样的,而这样的结果不是我们想要的。对于内建的基本类型来说,使用tpye来检查是没有问题的, 可是当应用到其他场合的时候,type就显得不可靠了。这个时候我们就需要使用isinstance来进行类型 检查。 isinstance(object, classinfo) object表示实例,classinfo可以是直接或间接类名、基本类型或者有它们组成的元组。 >>> isinstance(2, float) false >>> isinstance('a', (str, unicode)) true >>> isinstance((2, 3), (str, list, tuple)) true
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯