You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过面向对象编程修改float('inf')的显示为∞?

解决float('inf')显示为∞的问题

你的代码未生效有两个核心原因:

  1. 错误继承了float('inf')实例而非float类;
  2. print()调用的是对象的__str__方法,你仅重写了__repr__。

以下是正确的面向对象实现方案:

class Inf(float):
    def __new__(cls):
        # float是不可变类型,通过__new__创建实例并赋值为无穷大
        return super().__new__(cls, 'inf')
    
    def __str__(self):
        return '∞'
    
    def __repr__(self):
        return '∞'

inf = Inf()

效果验证

print(inf)          # 输出:∞
print(repr(inf))    # 输出:∞
print(inf * 100)    # 输出:∞(保留float的无穷大运算特性)

这个实现既保留了原生无穷大的数值计算能力,又能在打印或交互环境中显示为∞,达到类似sympy中oo的效果。

内容的提问来源于stack exchange,提问作者Oleg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:45:35