ITPub博客

首页 > IT职业 > IT图书 > Python常见工厂函数用法示例

Python常见工厂函数用法示例

IT图书 作者:jerrysun 时间:2021-09-09 09:41:23 0 删除 编辑

工厂函数:能够产生类实例的内建函数。

工厂函数是指这些内建函数都是类对象, 当调用它们时,实际上是创建了一个类实例。

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


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/151/viewspace-2806080/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-09-29

  • 博文量
    122
  • 访问量
    16194