Python __format__() 函数使用方法

549 阅读1分钟

语法

object.__format__(self, spec)

Python__format__() 方法实现了内置的 [format()](https://blog.finxter.com/python-format-function/)函数,以及 [string.format()](https://blog.finxter.com/python-string-format/)方法。因此,当你调用format(x, spec)string.format(spec) 时,Python 会尝试调用x.__format__(spec) 。其返回值是一个字符串。

我们称这种方法为*"* Dunder Method",即*"Double UnderscoreMethod"(也叫"Magic Method")*。要想获得所有带有解释的Dunder方法的列表,请查看我们博客上的Dunder cheat sheet文章

背景 format()

Python 内置的format(value, spec) 函数将一种格式的输入转换为你定义的另一种格式的输出。

具体来说,它将格式指定器spec 应用于参数value ,并返回一个格式化的表述value

例如,format(42, 'f') 返回字符串表示法'42.000000'

例子 自定义 __format__()

在下面的例子中,我们创建了一个自定义类Data ,并重写了__format__() 魔术方法,使其返回一个假字符串'hello world'

class Data:
    def __format__(self, spec):
        return 'hello ' + spec


x = Data()
print(format(x, 'world'))

这样,你可以为一个自定义对象创建你自己的小格式化语言。

class Data:
    def __format__(self, spec):
        if spec == '42':
            return 'finxter'
        return 'hello ' + spec
    

x = Data()

print(format(x, 'world'))
# hello world


print(format(x, '42'))
# finxter

在第一个 [print()](https://blog.finxter.com/python-print/)语句中,你使用了格式指定'world' ,它在你对__format__() 方法的自定义实现中没有特殊含义。因此,输出是'hello world'--字符串连接的结果'hello'格式指定符 'world'

在第二个print() 语句中,你使用了特殊的(根据你自己的定义)格式指定器'42'__format__() 方法现在返回一个特殊的字符串:'finxter'!