Why is not #39;decimal.Decimal(1)#39; an instance of #39;numbers.Real#39;?(为什么decimal.Decimal(1)不是numbers.Real的一个实例?)
问题描述
我尝试检查一个变量是否是任何类型(int、
float
、Fraction
、十进制
等).
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
code>十进制 数字...
The class numbers.Real
looked perfect but it returns False
for Decimal
numbers...
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
?
推荐答案
所以,我直接在cpython/numbers.py
:
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).
确实,将 Decimal
添加到 float
会引发 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'的一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么'decimal.Decimal(1)'不是'numbers.Real'的一个实例?


- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01