欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python常見工廠函數(shù)用法示例

 更新時間:2018年03月21日 10:15:44   作者:快遞小可  
這篇文章主要介紹了Python常見工廠函數(shù)用法,簡單描述了工廠函數(shù)的功能、定義并結(jié)合具體實例形式分析了Python常見工廠函數(shù)的相關(guān)使用技巧,需要的朋友可以參考下

本文實例講述了Python常見工廠函數(shù)用法。分享給大家供大家參考,具體如下:

工廠函數(shù):能夠產(chǎn)生類實例的內(nèi)建函數(shù)。

 工廠函數(shù)是指這些內(nèi)建函數(shù)都是類對象, 當(dāng)調(diào)用它們時,實際上是創(chuàng)建了一個類實例。

 python中的工廠函數(shù)舉例如下:

1》int(),long(),float(),complex(),bool()

>>> 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()

>>> s=str(9.9)
>>> s
'9.9'
>>> unicode(9.0)
u'9.0'
>>> unicode('love')
u'love'

3》list(),tuple():生成列表或者元組

>>> l=list('python')
>>> l
['p', 'y', 't', 'h', 'o', 'n']
>>> t=tuple('python')
>>> t
('p', 'y', 't', 'h', 'o', 'n')

4》type():查看類型

>>> 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():生成一個字典

>>> 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():   生產(chǎn)可變集合

>>> 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():生成不可變集合

>>> s=frozenset('python')
>>> s
frozenset(['h', 'o', 'n', 'p', 't', 'y'])
>>> s.add()#不可變集合
AttributeError: 'frozenset' object has no attribute 'add'

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

最新評論