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的字符串格式化功能中提供了一个钩子。需要强调的是,对格式化代码的解释完全取决于类本身。因此,格式化代码几乎可以为任何形式。

猜你喜欢

转载自blog.csdn.net/pengxuan3507/article/details/81535380