在 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
)
最佳答案
是,但使用 __format__
,而不是 __fstr__
。
f
-strings 并不是对以前格式化字符串的方法的彻底改造。相反,它建立在已经存在的协议(protocol)之上。
来自 PEP 0498在 Code equivalence 中介绍了它们:
The exact code used to implement f-strings is not specified. However, it is guaranteed that any embedded value that is converted to a string will use that value's
__format__
method. This is the same mechanism thatstr.format()
uses to convert values to strings.
然后,在 Format Specifiers 中:
Once expressions in a format specifier are evaluated (if necessary), format specifiers are not interpreted by the f-string evaluator. Just as in
str.format()
, they are merely passed in to the__format__()
method of the object being formatted.
因此,它们没有新特殊方法。您需要定义一个 __format__
方法,该方法采用规范并返回适当格式化的字符串。
作为 __format__
上的文档还描述:
Called by the
format()
built-in function, and by extension, evaluation of formatted string literals and thestr.format()
method, to produce a “formatted” string representation of an object.
关于python - 你能重载 Python 3.6 f-string 的 "operator"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081521/