【发布时间】:2019-08-29 20:05:28
【问题描述】:
“可比较”的意思是“能够相互执行比较操作>、<、>=、<=、== 和!= 而不会引发!=”。该属性确实适用于许多不同的类:
1 < 2.5 # int and float
2 < decimal.Decimal(4) # int and Decimal
"alice" < "bob" # str and str
(1, 2) < (3, 4) # tuple and tuple
但它没有:
1 < "2" # int and str
1.5 < "2.5" # float and str
即使看起来确实应该这样做:
datetime.date(2018, 9, 25) < datetime.datetime(2019, 1, 31) # date and datetime
[1, 2] < (3, 4) # list and tuple
As demonstrated in this similar question,您显然可以通过使用“请求宽恕,而不是许可”的传统 python 方法并使用 try/except 块来检查两个未知类型的对象 a 和 b :
try:
a < b
# do something
except TypeError:
# do something else
但是catching exceptions is expensive,我希望第二个分支足够频繁地被采用,所以我想在if/else 语句中抓住这一点。我该怎么做?
【问题讨论】:
-
简短的回答是这是不可能的,因为解释器永远不会知道比较方法是否会抛出
NotImplemented异常,直到该方法实际执行。底层机制的详细信息,请参考链接问题的答案。 -
如您的链接所示,异常处理非常便宜。它实际上不是免费的,但它很便宜,而且比您在此处避免异常处理所产生的所有开销要便宜得多。
标签: python comparison-operators