【问题标题】:Why is not 'decimal.Decimal(1)' an instance of 'numbers.Real'?为什么'decimal.Decimal(1)'不是'numbers.Real'的一个实例?
【发布时间】:2018-04-24 13:03:56
【问题描述】:

我尝试检查一个变量是否是任何类型(intfloatFractionDecimal 等)的实例。

我遇到了这个问题及其答案:How to properly use python's isinstance() to check if a variable is a number?

但是,我想排除复数,例如 1j

numbers.Real 类看起来很完美,但它为 Decimal 数字返回 False...

from numbers Real
from decimal import Decimal

print(isinstance(Decimal(1), Real))
# False

与此相反,例如 Fraction(1) 可以正常工作。

documentation 描述了一些应该使用数字的操作,我在十进制实例上测试它们没有任何错误。 此外,十进制对象不能包含复数。

那么,为什么isinstance(Decimal(1), Real) 会返回False

【问题讨论】:

  • @TomDalton 我读过它,但我还是不明白。 [isinstance(Decimal(1), t) for t in [Number, Complex, Real, Rational, Integral]] 返回[True, False, False, False, False]。如果DecimalNumber,为什么它不是它的任何子类?

标签: python numbers decimal isinstance


【解决方案1】:

所以,我直接在cpython/numbers.py的源码中找到了答案:

## 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).

确实,将Decimal 添加到float 会产生TypeError

在我看来,它违反了最小惊讶的原则,但没关系。

作为一种解决方法,我使用:

import numbers
import decimal

Real = (numbers.Real, decimal.Decimal)

print(isinstance(decimal.Decimal(1), Real))
# True

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 2010-10-03
    相关资源
    最近更新 更多