python 内建函数 type() 和 isinstance() 介绍

Python 不支持方法或函数重载, 因此你必须自己保证调用的就是你想要的函数或对象。一个名字里究竟保存的是什么?相当多,尤其是这是一个类型的名字时。确认接收到的类型对象的身份有很多时候都是很有用的。为了达到此目的,Python 提供了一个内建函数type(). type()返回任意Python 对象对象的类型,而不局限于标准类型。让我们通过交互式解释器来看几个使用type()内建函数返回多种对象类型的例子:

 1 >>> type('')
 2 <type 'str'>
 3 >>>
 4 >>> s = 'xyz'
 5 >>> type(s)
 6 <type 'str'>
 7 >>>
 8 >>> type(100)
 9 <type 'int'>
10 >>> type(0+0j)
11 <type 'complex'>
12 >>> type(0L)
13 <type 'long'>
14 >>> type(0.0)
15 <type 'float'>
16 >>>
17 >>> type([])
18 <type 'list'>
19 >>> type(())
20 <type 'tuple'>
21 >>> type({})
22 <type 'dict'>
23 >>> type(type)
24 <type 'type'>
25 >>>
26 >>> class Foo: pass # new-style class
27 ...
28 >>> foo = Foo()
29 >>> class Bar(object): pass # new-style class
30 ...
31 >>> bar = Bar()
32 >>>
33 >>> type(Foo)
34 <type 'classobj'>
35 >>> type(foo)
36 <type 'instance'>
37 >>> type(Bar)
38 <type 'type'>
39 >>> type(bar)
40 <class '__main__.Bar'>

Python2.2 统一了类型和类, 如果你使用的是低于Python2.2 的解释器,你可能看到不一样的输出结果。

 1 >>> type('')
 2 <type 'string'>
 3 >>> type(0L)
 4 <type 'long int'>
 5 >>> type({})
 6 <type 'dictionary'>
 7 >>> type(type)
 8 <type 'builtin_function_or_method'>
 9 >>>
10 >>> type(Foo) # assumes Foo created as in above
11 <type 'class'>
12 >>> type(foo) # assumes foo instantiated also
13 <type 'instance'>

 

posted @ 2016-07-30 16:14  淋哥  阅读(1217)  评论(0编辑  收藏  举报