Python常见工厂函数用法示例
来源 :中华考试网 2020-10-19
中工厂函数:能够产生类实例的内建函数。
工厂函数是指这些内建函数都是类对象, 当调用它们时,实际上是创建了一个类实例。
Python中的工厂函数举例如下:
1. int(),long(),float(),complex(),bool()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 |
>>> a = int ( 9.9 ) >>> a 9 >>> b = long ( 45 ) >>> b 45L >>> f = float ( 8 ) >>> f 8.0 >>> c = complex ( 8 ) >>> c ( 8 + 0j ) >>> b1 = bool ( 7.9 ) >>> b1 True >>> b2 = bool ( 0.0 ) >>> b2 False >>> b3 = bool ([]) >>> b2 False >>> b4 = bool (( 34 , 5 )) >>> b4 True |
2. str(),unicode()
1
2
3
4
5
6
7 |
>>> s = str ( 9.9 ) >>> s '9.9' >>> unicode ( 9.0 ) u '9.0' >>> unicode ( 'love' ) u 'love' |
3. list(),tuple():生成列表或者元组
1
2
3
4
5
6 |
>>> l = list ( 'python' ) >>> l [ 'p' , 'y' , 't' , 'h' , 'o' , 'n' ] >>> t = tuple ( 'python' ) >>> t ( 'p' , 'y' , 't' , 'h' , 'o' , 'n' ) |
4. type():查看类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
>>> type ( 6 ) < type 'int' > >>> type ( 'python' ) < type 'str' > >>> type (u 'love' ) < type 'unicode' > >>> class A(): ... pass ... >>> a = A() >>> type (a) < type 'instance' > >>> type (A) < type 'classobj' > |
5. dict():生成一个字典
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
>>> dict () {} >>> dict (one = 1 ,two = 2 ) { 'two' : 2 , 'one' : 1 } >>> dict ( zip (( 'one' , 'two' ),( 1 , 2 ))) { 'two' : 2 , 'one' : 1 } >>> dict ([( 'one' , 1 ),( 'two' , 2 )]) { 'two' : 2 , 'one' : 1 } >>> dict ([[ 'one' , 1 ],[ 'two' , 2 ]]) { 'two' : 2 , 'one' : 1 } >>> dict ((( 'one' , 1 ),( 'two' , 2 ))) { 'two' : 2 , 'one' : 1 } >>> dict (([ 'one' , 1 ],[ 'two' , 2 ])) { 'two' : 2 , 'one' : 1 } |
6. set(): 生产可变集合
1
2
3
4
5
6 |
>>> s = set ( 'python' ) >>> s set ([ 'h' , 'o' , 'n' , 'p' , 't' , 'y' ]) >>> s.add( 825 ) #可变集合 >>> s set ([ 'h' , 'o' , 'n' , 'p' , 't' , 'y' , 825 ]) |
7. frozenset():生成不可变集合
1
2
3
4
5 |
>>> s = frozenset ( 'python' ) >>> s frozenset ([ 'h' , 'o' , 'n' , 'p' , 't' , 'y' ]) >>> s.add() #不可变集合 AttributeError: 'frozenset' object has no attribute 'add' |