比较int和float时,Python何时执行类型转换? [英] When does Python perform type conversion when comparing int and float?
问题描述
当我比较具有相同值的int
和float
对象时,为什么Python返回True
?
Why does Python return True
when I compare int
and float
objects which have the same value?
例如:
>>> 5*2 == 5.0*2.0
True
推荐答案
它不像类型转换那样简单.
It's not as simple as a type conversion.
10 == 10.0
委托给参数的__eq__
方法,首先尝试(10).__eq__(10.0)
,然后在第一次调用返回NotImplemented
的情况下尝试(10.0).__eq__(10)
.它不尝试转换类型. (从技术上讲,方法查找使用一个特殊的例程,该例程绕过实例__dict__
条目和__getattribute__
/__getattr__
覆盖,因此,这并不等同于自己调用方法.)
10 == 10.0
delegates to the arguments' __eq__
methods, trying (10).__eq__(10.0)
first, and then (10.0).__eq__(10)
if the first call returns NotImplemented
. It makes no attempt to convert types. (Technically, the method lookup uses a special routine that bypasses instance __dict__
entries and __getattribute__
/__getattr__
overrides, so it's not quite equivalent to calling the methods yourself.)
int.__eq__
不知道如何处理浮点数:
int.__eq__
has no idea how to handle a float:
>>> (10).__eq__(10.0)
NotImplemented
但是float.__eq__
知道如何处理整数:
but float.__eq__
knows how to handle ints:
>>> (10.0).__eq__(10)
True
float.__eq__
也不只是在内部执行强制转换.它具有超过100行的代码处理浮点/整数比较,而不会产生未经检查的强制转换会导致的舍入错误. (如果C级比较例程不必同时处理>
,>=
,<
和<=
,则其中一些可以简化.)
float.__eq__
isn't just performing a cast internally, either. It has over 100 lines of code to handle float/int comparison without the rounding error an unchecked cast could introduce. (Some of that could be simplified if the C-level comparison routine didn't also have to handle >
, >=
, <
, and <=
.)
这篇关于比较int和float时,Python何时执行类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!