python __format__()自定义字符串的输出格式

我们可以让对象通过format()函数和字符串方法来支持自定义的输出格式。要自定义字符串的输出格式,可以在类中定义__format__()方法,如下:

In [6]: _formats = {'ymd' : '{d.year}-{d.month}-{d.day}',
   ...:             'mdy' : '{d.month}/{d.day}/{d.year}'}

In [12]: 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)

In [14]: d = Date(2018, 8, 8)

In [15]: format(d)
Out[15]: '2018-8-8'

    

__format__()方法在Python的字符串格式化功能中提供了一个钩子。需要强调的是,对格式化代码的解释完全取决于类本身。因此,格式化代码几乎可以为任何形式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值