首页 > 解决方案 > fractions.Fraction f 字符串作为带有 __format__ 的浮点数

问题描述

在 f 字符串中使用 afraction.Fraction时,我希望能够将其格式化为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__

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

有趣的是,它们适用于Decimal

from decimal import Decimal
f = Decimal('1.1')
f'{f} as float {f:.3f}'

有没有理由这不起作用Fraction

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

标签: pythonstring-formattingfractions

解决方案


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

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

    def __str__(self):
        return 'hello world'

如果我做

x = MyClass()
y = f"{x}"

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

我怀疑这Fraction门课就是这种情况,因为当你这样做 help(Fraction.__format__)

Help on method_descriptor:

__format__(self, format_spec, /)
    Default object formatter.

推荐阅读