2017-11-11 103 views
1

我尝试检查一个变量是否是任何类型的数字(int,floatFractionDecimal等)的一个实例。为什么不是 'decimal.Decimal(1)' 的 'numbers.Real' 的实例?

我翻过凸轮这个问题,它的答案是:How to properly use python's isinstance() to check if a variable is a number?

不过,我想排除复数,如1j

numbers.Real看上去完美,但它返回FalseDecimal数...

from numbers Real 
from decimal import Decimal 

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

在矛盾,它正常工作与Fraction(1)例如。

documentation介绍了一些操作,这些操作应与数工作,我对它们进行测试没有任何错误在小数实例。 另外,小数对象不能包含复数。

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

+1

https://docs.python.org/3.6/library/numbers.html#the-numeric-tower –

+0

@TomDalton我读了它,但我仍然不明白。 '[isinstance(十进制(1)中,t)对于t在[号码,复杂的,真实的,理性,积分]]'返回'[真,FALSE,FALSE,FALSE,FALSE]'。如果一个'Decimal'是一个'Number',为什么它不是它的子类? – Delgan

回答

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

事实上,加入Decimalfloat将提高TypeError

在我的角度来看,它违反了最小惊讶的原则,但它并没有多大关系。

作为一种变通方法,我用:

import numbers 
import decimal 

Real = (numbers.Real, decimal.Decimal) 

print(isinstance(decimal.Decimal(1), Real)) 
# True 
相关问题