__format__
发布日期:2021-05-09 05:34:01 浏览次数:7 分类:博客文章

本文共 632 字,大约阅读时间需要 2 分钟。

目录
Python从入门到放弃完整教程目录:

一、__format__

  • 自定制格式化字符串
date_dic = {    'ymd': '{0.year}:{0.month}:{0.day}',    'dmy': '{0.day}/{0.month}/{0.year}',    'mdy': '{0.month}-{0.day}-{0.year}',}class Date:    def __init__(self, year, month, day):        self.year = year        self.month = month        self.day = day    def __format__(self, format_spec):        # 默认打印ymd的{0.year}:{0.month}:{0.day}格式        if not format_spec or format_spec not in date_dic:            format_spec = 'ymd'        fmt = date_dic[format_spec]        return fmt.format(self)d1 = Date(2016, 12, 29)
print(format(d1))
2016:12:29
print('{:mdy}'.format(d1))
12-29-2016
上一篇:实现迭代器(__next__和__iter__)
下一篇:__call__

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月03日 00时08分19秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章