Python常见工厂函数的解决办法
内容摘要
这篇文章主要为大家详细介绍了Python常见工厂函数的简单示例,具有一定的参考价值,可以用来参考一下。
对python这个高级语言对此感兴趣的朋友,看看idc笔记做的技术笔记!
工厂函
对python这个高级语言对此感兴趣的朋友,看看idc笔记做的技术笔记!
工厂函
文章正文
这篇文章主要为大家详细介绍了Python常见工厂函数的简单示例,具有一定的参考价值,可以用来参考一下。
对python这个高级语言对此感兴趣的朋友,看看idc笔记做的技术笔记!工厂函数:能够产生类实例的内建函数。
工厂函数是指这些内建函数都是类对象, 当调用它们时,实际上是创建了一个类实例。
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 25 26 27 28 29 30 31 | <code class = "python" > # @param Python常见工厂函数用法示例 # @author php教程|512PiC.com >>> 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 # End www_512pic_com </code> |
2. str(),unicode()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <code class = "python" > # @param Python常见工厂函数用法示例 # @author php教程|512PiC.com >>> s=str(9.9) >>> s '9.9' >>> unicode(9.0) u '9.0' >>> unicode( 'love' ) u 'love' # End www_512pic_com </code> |
3. list(),tuple():生成列表或者元组
1 2 3 4 5 6 7 8 9 10 11 12 13 | <code class = "python" > # @param Python常见工厂函数用法示例 # @author php教程|512PiC.com >>> l=list( 'python' ) >>> l [ 'p' , 'y' , 't' , 'h' , 'o' , 'n' ] >>> t=tuple( 'python' ) >>> t ( 'p' , 'y' , 't' , 'h' , 'o' , 'n' ) # End www_512pic_com </code> |
4. type():查看类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <code class = "python" > # @param Python常见工厂函数用法示例 # @author php教程|512PiC.com >>> 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' > # End www_512pic_com </code> |
5. dict():生成一个字典
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <code class = "python" > # @param Python常见工厂函数用法示例 # @author php教程|512PiC.com >>> 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} # End www_512pic_com </code> |
6. set(): 生产可变集合
1 2 3 4 5 6 7 8 9 10 11 12 13 | <code class = "python" > # @param Python常见工厂函数用法示例 # @author php教程|512PiC.com >>> s=set( 'python' ) >>> s set([ 'h' , 'o' , 'n' , 'p' , 't' , 'y' ]) >>> s.add(825)#可变集合 >>> s set([ 'h' , 'o' , 'n' , 'p' , 't' , 'y' , 825]) # End www_512pic_com </code> |
7. frozenset():生成不可变集合
1 2 3 4 5 6 7 8 9 10 11 12 | <code class = "python" > # @param Python常见工厂函数用法示例 # @author php教程|512PiC.com >>> s=frozenset( 'python' ) >>> s frozenset([ 'h' , 'o' , 'n' , 'p' , 't' , 'y' ]) >>> s.add()#不可变集合 AttributeError: 'frozenset' object has no attribute 'add' # End www_512pic_com </code> |
注:关于Python常见工厂函数的简单示例的内容就先介绍到这里,更多相关文章的可以留意
代码注释