所以我有一个班轮:
import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01))
它所做的只是创建一个包含 100.0 的 Decimal 对象,并以各种方式将其与 0.01(浮点数)进行比较。
我的结果是:
>>> import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01))
(False, True, NotImplemented, NotImplemented)
来自文档:“如果丰富的比较方法没有实现给定参数对的操作,则它可能会返回单例 NotImplemented。”
所以这里确实存在三个问题。
当丰富的比较方法返回 NotImplemented 时,会发生什么?为什么它不引发异常?
当它获得 NotImplemented 时,为什么在第一种情况下返回 False,而在第二种情况下返回 True? bool(NotImplemented) 应该是一个常量。
它只是简单地退回到 id() 检查吗?似乎没有(或者是,但倒退):
(忽略这一行,格式搞砸了,这可以修复它)
from decimal import Decimal
h = Decimal('100.0')
f = .01
print h < f, id(h) < id(f)
print h > f, id(h) > id(f)
我的结果经过测试:
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32
编辑:有关订购的文档:http://docs.python.org/library/stdtypes.html#comparisons http://docs.python.org/library/stdtypes.html#comparisons