W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
你想通過(guò) format()
函數(shù)和字符串方法使得一個(gè)對(duì)象能支持自定義的格式化。
為了自定義字符串的格式化,我們需要在類上面定義 __format__()
方法。例如:
_formats = {
'ymd' : '{d.year}-{d.month}-{d.day}',
'mdy' : '{d.month}/{d.day}/{d.year}',
'dmy' : '{d.day}/{d.month}/{d.year}'
}
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)
現(xiàn)在 Date
類的實(shí)例可以支持格式化操作了,如同下面這樣:
>>> d = Date(2012, 12, 21)
>>> format(d)
'2012-12-21'
>>> format(d, 'mdy')
'12/21/2012'
>>> 'The date is {:ymd}'.format(d)
'The date is 2012-12-21'
>>> 'The date is {:mdy}'.format(d)
'The date is 12/21/2012'
>>>
__format__()
方法給Python的字符串格式化功能提供了一個(gè)鉤子。這里需要著重強(qiáng)調(diào)的是格式化代碼的解析工作完全由類自己決定。因此,格式化代碼可以是任何值。例如,參考下面來(lái)自 datetime
模塊中的代碼:
>>> from datetime import date
>>> d = date(2012, 12, 21)
>>> format(d)
'2012-12-21'
>>> format(d,'%A, %B %d, %Y')
'Friday, December 21, 2012'
>>> 'The end is {:%d %b %Y}. Goodbye'.format(d)
'The end is 21 Dec 2012. Goodbye'
>>>
對(duì)于內(nèi)置類型的格式化有一些標(biāo)準(zhǔn)的約定??梢詤⒖?string模塊文檔 說(shuō)明。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: