本文實例講述了Python常見工廠函數用法。分享給大家供大家參考,具體如下:
工廠函數:能夠產生類實例的內建函數。
工廠函數是指這些內建函數都是類對象, 當調用它們時,實際上是創建了一個類實例。
python中的工廠函數舉例如下:
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(): 生產可變集合
>>> 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'希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答