gpt4 book ai didi

python - 为什么 Decimal ('0' ) > 9999.0 在 Python 中为真?

转载 作者:太空狗 更新时间:2023-10-30 00:30:43 24 4
gpt4 key购买 nike

这在某种程度上与我的问题 Why is ''>0 True in Python? 有关

在 Python 2.6.4 中:

>> Decimal('0') > 9999.0
True

来自answer对于我原来的问题,我知道在 Python 2.x 中比较不同类型的对象时,类型是按名称排序的。但在这种情况下:

>> type(Decimal('0')).__name__ > type(9999.0).__name__
False

为什么 Decimal('0') > 9999.0 == True 呢?

更新:我通常在 Ubuntu (Linux 2.6.31-20-generic#57-Ubuntu SMP Mon Feb 8 09:05:19 UTC 2010 i686 GNU/Linux, Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [Linux2 上的 GCC 4.4.1])。在 Windows(WinXP Professional SP3,Python 2.6.4(r264:75706,2009 年 11 月 3 日,13:23:17)[MSC v.1500 32 位(英特尔)] on win32 上)我的原始语句的工作方式不同:

>> Decimal('0') > 9999.0
False

我现在更疑惑了。 %-(

最佳答案

因为 decimal 模块不与除 long、int 和 Decimal 之外的任何类型进行比较。在所有其他情况下,decimal 默默地返回“不是它所知道的关于对象的东西”。您可以在 decimal.py 的 _convert_other() 函数中看到此行为

愚蠢,愚蠢的 Decimal 类。

哦,看http://bugs.python.org/issue2531也是。

所以,这是发生了什么:

  • 解释器调用Decimal.__gt__ 比较函数。
  • Decimal.__gt__ 调用 Decimal._convert_other 将传入的 float 转换为 Decimal。
  • Decimal._convert_other 不理解 float 。 Decimal._convert_other 中的实现显式检查操作数的 longintDecimal 类型。对,这就是一个错误,因为意外的库实现会导致进一步的错误。它做正确的事甚至只是通过 TypeException 会更干净。反而它通过相同的 NotImplemented 将 Decimal 与,比方说,员工记录的哈希值。
  • 尝试了其他一些比较操作。比较放弃。
  • 默认比较,在 CPython 的 Objects/object.c/default_3way_compare 中被调用。
  • 在 Python 3 中,这确实令人厌恶。在 Python 2 中,它比较 id() 函数。
  • 在 Windows 上,使用(某种程度上)不区分大小写的比较。在现代系统中,一个使用区分大小写的比较。
  • 所以你会得到不同的结果。

我们到了吗?

关于python - 为什么 Decimal ('0' ) > 9999.0 在 Python 中为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com