工厂函数:能够产生类实例的内建函数。
工厂函数是指这些内建函数都是类对象, 当调用它们时,实际上是创建了一个类实例。
Python中的工厂函数举例如下:
1. int(),long(),float(),complex(),bool()
123456789101112131415161718192021222324 | >>> 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()
1234567 | >>> s = str ( 9.9 ) >>> s '9.9' >>> unicode ( 9.0 ) u '9.0' >>> unicode ( 'love' ) u 'love' |
3. list(),tuple():生成列表或者元组
123456 | >>> l = list ( 'python' ) >>> l [ 'p' , 'y' , 't' , 'h' , 'o' , 'n' ] >>> t = tuple ( 'python' ) >>> t ( 'p' , 'y' , 't' , 'h' , 'o' , 'n' ) |
4. type():查看类型
1234567891011121314 | >>> 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():生成一个字典
1234567891011121314 | >>> 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(): 生产可变集合
123456 | >>> 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():生成不可变集合
12345 | >>> s = frozenset ( 'python' ) >>> s frozenset ([ 'h' , 'o' , 'n' , 'p' , 't' , 'y' ]) >>> s.add() #不可变集合 AttributeError: 'frozenset' object has no attribute 'add' |
原文来源:https://www.pythontab.com/html/2018/pythonjichu_0321/1263.html
打开App,阅读手记