Python常見工廠函數用法樣本,python工廠樣本

來源:互聯網
上載者:User

Python常見工廠函數用法樣本,python工廠樣本

本文執行個體講述了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'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.