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'的一个实例?


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01