在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.Formatter
类中提供的方法,例如get_field
、get_value
、check_unused_args
、format_field
和convert_field
,以获得对format
函数行为的更详细控制。 - Rick