2017-11-11 107 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 
相關問題