8.2 自定義字符串的格式化

2018-02-24 15:26 更新

問(wèn)題

你想通過(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ō)明。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)