首页 > 解决方案 > 创建 float 的子类,以防所有算术运算都返回同一类的对象(不是 float)

问题描述

我的课堂示例:

class Ff(float):
    def __str__(self):
        return '{:.2f}'.format(self) + '$'

a = Ff(1)
print(type(a))
print(a)

返回:

<class '__main__.Ff'>
1.00$

但万一:

a = Ff(1) + 2
print(type(a))
print(a)

返回:

<class 'float'>
3.0

如何在结果中添加Ff(1) + 2或为 radd2 + Ff(1)获得相同的 <class ' main .Ff'> ?

标签: pythonoop

解决方案


推荐阅读