【发布时间】:2018-04-15 08:16:05
【问题描述】:
在 Python 3.6 中,您可以使用 f-strings 喜欢:
>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'
我想重载接收上述'%A' 的方法。可以做到吗?
例如,如果我想为 datetime 编写一个愚蠢的包装器,我可能希望这种重载看起来像:
class MyDatetime:
def __init__(self, my_datetime, some_other_value):
self.dt = my_datetime
self.some_other_value = some_other_value
def __fstr__(self, format_str):
return (
self.dt.strftime(format_str) +
'some other string' +
str(self.some_other_value
)
【问题讨论】:
-
为了获得更大的灵活性,您可以覆盖
string.Formatterclass 中提供的方法 - 例如get_field、get_value、check_unused_args、format_field和convert_field- 以对format函数行为进行更详细的控制。
标签: python python-3.x python-3.6 f-string