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 @   做梦当财神  阅读(66)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2017-12-20 Oracle(限定查询1)
2017-12-20 Oracle其他简单查询
2017-12-20 Oracle简单语句查询
点击右上角即可分享
微信分享提示