python - 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}'
但我在问为什么需要这样做。
解决方案
如果你没有__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.
推荐阅读
- javascript - 表格中的表格 pdfmake
- c# - 从控制台按键取消异步方法
- r - 尝试在使用 R Shiny 时发现错误
- powershell - 使用产品 ID 生成产品 URL
- git - 在 Visual Studio Code 中暂存单个已删除的行
- mysql - 多级订阅 Web 应用程序的理想 mysql 数据库结构是什么?
- postgresql - 从 jsp 连接到 postgresql
- html - 两张图没有排成一行
- ruby-on-rails - 让我的 Ruby on Rails 页面在不使用设计的情况下保存用户的电子邮件
- pdf - 如何将 PDF 呈现为 BMP,以使内容适合 PDF 页面边界?