【问题标题】:Why isn't a Decimal an instance of the Real number abstract base class? [duplicate]为什么 Decimal 不是实数抽象基类的实例? [复制]
【发布时间】:2019-04-12 16:58:36
【问题描述】:

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

from numbers import Real
from decimal import Decimal

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

这很容易通过将Decimal注册为子类来改变:

Real.register(Decimal)

但这让我问了一个问题:为什么Decimal一开始就没有以这种方式注册?是否有一些实际原因或设计原因,对十进制实例做出这种假设是个坏主意?

【问题讨论】:

  • 我认为您可以将此视为这些 ABC 的采用率有多低的标志。
  • @user2357112 公平点。我是这个星球上唯一一个我见过尝试利用它们的人。
  • 我发誓我搜索了这个问题,但没有找到任何东西。我怎么会错过那个重复的?嗯。

标签: python


【解决方案1】:

答案在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).

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

【讨论】:

  • 源代码行503 也表达了基本相同的内容:_pydecimal.py。但它引用了您在上面粘贴的numbers。
猜你喜欢
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 2015-07-11
  • 2014-06-24
  • 2012-07-04
  • 1970-01-01
相关资源
最近更新 更多