python - 你能重载 Python 3.6 f-string 的 "operator"吗?

标签 python python-3.x python-3.6 f-string

在 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 0498Code 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 that str.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 the str.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/

相关文章:

python - 如何清理 pandas 数据框中的图像格式?

python - 在spyder ipython中启用subprocess.run的打印

linux - 通过终端在 Raspberry pi 中同时运行多个 cmdline 命令或文件

python - 从具有相同行的向量替换给定索引的numpy数组列中的值

python - Zemanta 和 Open Calais 等内容发现引擎如何工作?

python - python 3中的简单多线程

python - 使用类型注释记录类属性

python - 非法指令: 4 when importing python pandas

python - 如何在 python 中用字符串填充矩阵的对角线?

Python 3 if-else 简写命令语法错误