如果使用 type 进行类型检查,会存在一些问题。

问题一、假如开发者基于内建类型扩展的用户自定义类型,type 函数并不能准确返回结果。

import types
class UserInt(int) :
    def __init__(self, val=0) :
        self._val = int(val)
    def __add__(self, val) :
        if isinstance(val,UserInt):
            return UserInt(self._val + val._val)
        return self._val + val
    def __iadd__(self, val) :
        raise NotImplementedError("not support operation")
    def __str__(self) :
        return str(self._val)
    def __repr__(self) :
        return 'Integer(%s)' %self._val
n = UserInt()
print type(n) is types.IntType    # False

问题二、在古典类中,所有类的实例的 type 值都相等。在古典类中,任意类的实例的 type()返回结果都是 <type 'instance'>

class A:
 pass
 
class B:
 pass
 
a = A()
b = B()
type(a) == type(b)  # True

用 isinstance 函数来检测。

isinstance(object, classinfo)
 
isinstance(2,float) # False
isinstance("a",(str,unicode)) # True
isinstance((2,3),(str,list,tuple)) # True