type函数可以检测任何值或变量的类型。
例子:
1 def printType(var): 2 print(type(var)) 3 4 class TestClass: 5 pass 6 7 printType(1) 8 printType(1.5) 9 printType('str') 10 printType(True) 11 printType(['a','b','c']) 12 printType(('a','b','c')) 13 printType(set(['a','b','c'])) 14 printType({'Tom':18,'Lily':20}) 15 printType(printType) 16 printType(TestClass) 17 printType(TestClass())
将会依次输出:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
<class 'function'>
<class 'type'>
<class '__main__.TestClass'>
type函数相当于C#中的typeof和GetType的混合体