为什么'decimal.Decimal(1)'不是'numbers.Real'的实例? [英] Why is not 'decimal.Decimal(1)' an instance of 'numbers.Real'?
问题描述
我尝试检查变量是否是任何类型(int
,float
,Fraction
,Decimal
等)的实例.
I try to check if a variable is an instance of a number of any type (int
, float
, Fraction
, Decimal
, etc.).
我遇到了这个问题及其答案:如何正确使用python的isinstance()检查变量是否为数字?
I cam accross this question and its answer: How to properly use python's isinstance() to check if a variable is a number?
但是,我想排除诸如1j
的复数.
However, I would like to exclude complex numbers such as 1j
.
类 numbers.Real
看起来很完美,但返回了False
用于 Decimal
数字... >
from numbers Real
from decimal import Decimal
print(isinstance(Decimal(1), Real))
# False
矛盾的是,它与 Fraction(1)
正常工作例如.
In contradiction, it works fine with Fraction(1)
for example.
文档描述了一些应与数字,我在十进制实例上对它们进行了测试,没有任何错误. 此外,小数对象不能包含复数.
The documentation describes some operations which should work with the number, I tested them without any error on a decimal instance. Decimal objects cannot contains complex numbers moreover.
那么,为什么isinstance(Decimal(1), Real)
将返回False
?
So, why isinstance(Decimal(1), Real)
would return False
?
推荐答案
So, I found the answer directly in the source code of 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).
实际上,在float
上添加Decimal
会产生一个TypeError
.
Indeed, adding Decimal
to float
would raise a TypeError
.
在我看来,它违反了最小惊讶原则,但没什么大不了.
In my point of view, it violates the principle of least astonishment, but it does not matter much.
作为一种解决方法,我使用:
As a workaround, I use:
import numbers
import decimal
Real = (numbers.Real, decimal.Decimal)
print(isinstance(decimal.Decimal(1), Real))
# True
这篇关于为什么'decimal.Decimal(1)'不是'numbers.Real'的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!