您可以重载Python 3.6 f字符串的"operator"吗? [英] Can you overload the Python 3.6 f-string's "operator"?
问题描述
在Python 3.6中,您可以使用 f字符串,例如:
In Python 3.6, you can use f-strings like:
>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'
我想重载接收上述'%A'
的方法.能做到吗
I want to overload the method receiving the '%A'
above. Can it be done?
例如,如果我想在datetime
周围编写一个哑包,我可能希望这种重载看起来像:
For example, if I wanted to write a dumb wrapper around datetime
, I might expect this overloading to look something like:
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
-字符串不是对格式化字符串的先前方法的全面检查.相反,它基于已经存在的协议.
f
-strings were not an overhaul of the previous methods to format strings. Instead, it built on the protocols already in place.
来自 PEP 0498 ,并在
未指定用于实现f字符串的确切代码.但是,可以保证任何转换为字符串的嵌入值都将使用该值的 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 ,然后再次在格式说明符中: 一旦对格式说明符中的表达式进行了评估(如有必要),则f字符串评估程序不会解释格式说明符.就像在 Once expressions in a format specifier are evaluated (if necessary), format specifiers are not interpreted by the f-string evaluator. Just as in 因此,没有针对他们的 new 特殊方法.您需要定义一个采用规范并返回格式正确的字符串的 So, there's no new special method for them. You need to define a As the docs on 由 Called by the 这篇关于您可以重载Python 3.6 f字符串的"operator"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!__format__
方法.这与str.format()
用来将值转换为字符串的机制相同.
__format__
method. This is the same mechanism that str.format()
uses to convert values to strings.
str.format()
中一样,它们只是传递给要格式化的对象的__format__()
方法.
str.format()
, they are merely passed in to the __format__()
method of the object being formatted.__format__
方法. __format__
method that takes the spec and returns an appropriately formatted string. __format__
上的文档也描述了: __format__
also describe:
format()
内置函数调用,并通过扩展调用格式化字符串文字的评估和str.format()
方法,以生成对象的格式化"字符串表示形式./p>
format()
built-in function, and by extension, evaluation of formatted string literals and the str.format()
method, to produce a "formatted" string representation of an object.