2017-11-11 5 views
1

変数が任意の数のインスタンス(intfloatFractionDecimalなど)であるかどうかを確認しようとします。'decimal.Decimal(1)'が 'numbers.Real'のインスタンスではないのはなぜですか?

私はこの質問とその答えaccrossカム:しかし、私は、このような1jなどの複雑な数字を除外したいHow to properly use python's isinstance() to check if a variable is a number?

クラスnumbers.Realは完璧に見えたが、それはDecimal数字...矛盾で

from numbers Real 
from decimal import Decimal 

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

ためFalseを返し、それが例えばFraction(1)で正常に動作します。

documentationには、数字で動作する操作がいくつか記載されていますが、小数点以下の例でエラーなしでテストしました。 10進数のオブジェクトには複素数を含めることはできません。

だから、なぜisinstance(Decimal(1), Real)Falseを返すのですか?

+1

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

+0

@TomDalton私はそれを読んで、まだI理解していない。 [Number、Complex、Real、Rational、Integral]の '[isinstance(Decimal(1)、t)'は '[True、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). 

を、TypeErrorを引き上げるfloatDecimalを追加します。

私の見解では、それは最も驚くべきことの原則に違反しますが、それほど重要ではありません。

は回避策として、私が使用します。

import numbers 
import decimal 

Real = (numbers.Real, decimal.Decimal) 

print(isinstance(decimal.Decimal(1), Real)) 
# True 
関連する問題