分数.f字符串作为__format__的float

fiz*_*h2o 5 python string-formatting fractions

当使用fraction.Fraction在F-字符串我希望能够格式化为一个float。但是我得到了TypeError

from fractions import Fraction
f = Fraction(11/10)
f'{f} as float {f:.3f}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to Fraction.__format__
Run Code Online (Sandbox Code Playgroud)

似乎可以/应该支持浮点格式规范Fractions

有趣的是,它们用于Decimal

from decimal import Decimal
f = Decimal('1.1')
f'{f} as float {f:.3f}'
Run Code Online (Sandbox Code Playgroud)

这有什么原因不起作用Fraction吗?

是的,我知道我可以做,f'{f} as float {float(f):.3f}'但是我在问为什么要这样做。

Jua*_*rez 3

如果您没有__format__在类中实现该方法,那么您将自动获得默认格式化程序,该格式化程序仅应用 str 方法。考虑

class MyClass:
    """A simple example class"""

    def __str__(self):
        return 'hello world'
Run Code Online (Sandbox Code Playgroud)

如果我做

x = MyClass()
y = f"{x}"
Run Code Online (Sandbox Code Playgroud)

那么y就会有价值"Hello World"。这是因为我得到了默认格式化程序,它调用我的__str__.

我怀疑班级就是这种情况Fraction,因为当你这样做时, help(Fraction.__format__) 你会得到

x = MyClass()
y = f"{x}"
Run Code Online (Sandbox Code Playgroud)