本文實例講述了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)>>> a9>>> b=long(45)>>> b45L>>> f=float(8)>>> f8.0>>> c=complex(8)>>> c(8+0j)>>> b1=bool(7.9)>>> b1True>>> b2=bool(0.0)>>> b2False>>> b3=bool([])>>> b2False>>> b4=bool((34,5))>>> b4True
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')>>> sset(['h', 'o', 'n', 'p', 't', 'y'])>>> s.add(825)#可變集合>>> sset(['h', 'o', 'n', 'p', 't', 'y', 825])7》frozenset():生成不可變集合
>>> s=frozenset('python')>>> sfrozenset(['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īng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
|
新聞熱點
疑難解答
圖片精選