如何通过面向对象编程修改float('inf')的显示为∞?
解决float('inf')显示为∞的问题
你的代码未生效有两个核心原因:
- 错误继承了
float('inf')实例而非float类; 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
相关产品推荐
相关产品推荐

