Python中的类型检查
在Python中,类型检查是通过内置函数isinstance()来实现的。
isinstance() 函数用于判断一个对象是否是一个已知的类型,类似 type()。
isinstance() 与 type() 区别:
type() 不会认为子类是一种父类类型。 isinstance() 会认为子类是一种父类类型。
语法 isinstance(object, classinfo)
参数 object -- 实例对象。 classinfo -- 可以是直接或间接类名、基本类型或者由基本类型组成的元组。
返回值 如果对象的类型与参数二的类型(或者其父类型)相同则返回 True,否则返回 False。
实例 以下实例展示了 isinstance 的使用方法:
实例(Python 2.0+) !/usr/bin/python
a = 200 b = int
if isinstance(a, b): print "A is instance of B" else : print "A is not instance of B"
实例(Python 2.2+) !/usr/bin/python
a = 200 b = int
if isinstance(a, b): print "A is instance of B" else : print "A is not instance of B"
if type(a) is b: print "A is type of B" else : print "A is not type of B" 以上实例输出结果:
A is instance of B A is type of B