Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
您能否重载Python 3.6 f-string';s";运营商;?_Python_Python 3.x_Python 3.6_F String - Fatal编程技术网

您能否重载Python 3.6 f-string';s";运营商;?

您能否重载Python 3.6 f-string';s";运营商;?,python,python-3.x,python-3.6,f-string,Python,Python 3.x,Python 3.6,F String,在Python 3.6中,您可以使用以下命令: 我想重载接收上述'%A'的方法。能做到吗 例如,如果我想围绕datetime编写一个哑包装器,我可能会认为这种重载看起来像: class MyDatetime: def __init__(self, my_datetime, some_other_value): self.dt = my_datetime self.some_other_value = some_other_value def __

在Python 3.6中,您可以使用以下命令:

我想重载接收上述
'%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
        )
是的,但是通过使用
\uuuuuu格式\uuuuuu
,而不是
\uuuuu fstr\uuuu


f
-字符串并不是以前格式化字符串的方法的翻修。相反,它建立在已经存在的协议之上

从中介绍了他们,在:

未指定用于实现f字符串的确切代码。但是,可以保证,任何转换为字符串的嵌入值都将使用该值的
\uuuuuu格式\uuuuu
方法。这与
str.format()
用于将值转换为字符串的机制相同

然后,在:

一旦对格式说明符中的表达式求值(如有必要),格式说明符就不会被f字符串求值器解释。就像在
str.format()
中一样,它们只会被传递到正在格式化的对象的
\uuuuuu format()
方法中

因此,没有新的特殊方法来解决这些问题。您需要定义一个
\uuuuuuuuuuuuuuuuuuuuuuuuuu
方法,该方法接受规范并返回适当格式的字符串

正如上的文档所述:

format()
内置函数调用,并扩展为格式化字符串文本的求值和
str.format()
方法,以生成对象的“格式化”字符串表示形式


。为了获得更大的灵活性,您可以覆盖-中提供的方法,例如
获取字段
获取值
检查未使用的参数
格式字段
,以及
转换字段
,以便对
格式
函数行为进行更详细的控制。
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
        )