你可以在运行时检查任何对象的数据类型,这样你的程序就能够正确处理不同类型的数据(例如,一个 int 函数,你传给它一个整数、浮点数、字符串,等等,它都能工作)。用 type(obj) 就能获取任何对象的类型:
>>> type(5)
<type ‘int’>
>>> type(‘She sells seashells’)
<type ‘string’>
>>> type(operator)
<type ‘module’>
types 模块包含了Python内置数据类型的 type objects。
>>> import types
>>> def upEm(words):
... if type(words) != types.ListType: # Not a list so
... words = [words] # make it a list.
... for word in words:
... print word.upper()
>>> upEm(‘horse’)
HORSE
>>> upEm([‘horse’,’cow’,’sheep’])
HORSE
COW
SHEEP
classes 的 Classes 和 instances 分别拥有类型 ClassType 和 InstanceType。
>>> isinstance(5.1,types.FloatType)
1
>>> class Foo:
... pass
...
>>> a = Foo()
>>> isinstance(a,Foo)
1