Python format() 高级

Python format() 基础。

一、问题

通过format()函数和字符串方法使对象能支持自定义的格式化。


二、解决方案

为了自定义字符串的格式化,需要在类上面定义__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 == '':      # 如果为空,默认'ymd'
            code = 'ymd'
        fmt = _formats[code]
        print('fmt:',fmt)
        return fmt.format(d=self)

d = Date(2021, 12, 20)
print(format(d))
print(format(d, 'mdy'))

输出:

fmt: {d.year}-{d.month}-{d.day}
2021-12-20
fmt: {d.month}/{d.day}/{d.year}
12/20/2021

三、讨论

__format__()方法给 Python 的字符串格式化功能提供了一个钩子。这里需要强调的是格式化代码的解析工作由类自己决定。因此,格式化代码可以是任何值。

from datetime import date

d = date(2021, 12, 20)
print(format(d))
print(format(d, '%A, %B, %d, %Y'))
print('The end is {:%d %b %Y}. Goodbye'.format(d))

输出:

2021-12-20
Monday, December, 20, 2021
The end is 20 Dec 2021. Goodbye


posted @ 2021-12-20 12:44  做梦当财神  阅读(58)  评论(0编辑  收藏  举报