我想扩展Decimal类,为它添加一些有用的方法,特别是为了处理钱.
当我这样做时的问题:
from decimal import Decimal
class NewDecimal(Decimal):
def new_str(self):
return "${}".format(self)
d1 = NewDecimal(1)
print d1.new_str() # prints '$1'
d2 = NewDecimal(2)
d3 = NewDecimal(3)
d5 = d2 + d3
print d5.new_str() #exception happens here
Run Code Online (Sandbox Code Playgroud)
它引发了一个异常:
AttributeError: 'Decimal' object has no attribute 'new_str'
Run Code Online (Sandbox Code Playgroud)
这是因为Decimal进行算术的方式,它总是返回一个新的Decimal对象,通过在计算结束时字面上调用Decimal(新值).
除了完全重新实现所有算术之外,有没有人没有解决方法?