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


基础教程推荐
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01