您可以重载Python 3.6 f字符串的"operator"吗? [英] Can you overload the Python 3.6 f-string's "operator"?

查看:67
本文介绍了您可以重载Python 3.6 f字符串的"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字符串的确切代码.但是,可以保证任何转换为​​字符串的嵌入值都将使用该值的__format__方法.这与str.format()用来将值转换为字符串的机制相同.

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.

,然后再次在格式说明符中:

一旦对格式说明符中的表达式进行了评估(如有必要),则f字符串评估程序不会解释格式说明符.就像在str.format()中一样,它们只是传递给要格式化的对象的__format__()方法.

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.

因此,没有针对他们的 new 特殊方法.您需要定义一个采用规范并返回格式正确的字符串的__format__方法.

So, there's no new special method for them. You need to define a __format__ method that takes the spec and returns an appropriately formatted string.

__format__ 上的文档也描述了:

As the docs on __format__ also describe:

format()内置函数调用,并通过扩展调用格式化字符串文字的评估str.format()方法,以生成对象的格式化"字符串表示形式./p>

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 3.6 f字符串的"operator"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆