为什么Decimal不是Real number抽象基类的实例?

时间:2019-04-12 16:58:37

标签: python

当前未指定python Decimal对象为Real抽象基类的子类:

from numbers import Real
from decimal import Decimal

isinstance(Decimal("1.0"), numbers.Real) #  False

通过将Decimal注册为子类可以轻松更改:

Real.register(Decimal)

但这让我问一个问题:为什么Decimal最初没有这样注册?是否存在一些实际原因或设计原因,对十进制实例进行这种假设是一个坏主意?

1 个答案:

答案 0 :(得分:4)

答案来自numbers module来源:

## Notes on Decimal
## ----------------
## Decimal has all of the methods specified by the Real abc, but it should
## not be registered as a Real because decimals do not interoperate with
## binary floats (i.e.  Decimal('3.14') + 2.71828 is undefined).  But,
## abstract reals are expected to interoperate (i.e. R1 + R2 should be
## expected to work if R1 and R2 are both Reals).

我认为他们可能可以将其添加到文档中。