When does Python perform type conversion when comparing int and float?

前端 未结 7 1424
太阳男子
太阳男子 2021-01-12 23:22

Why does Python return True when I compare int and float objects which have the same value?

For example:

>&         


        
7条回答
  •  星月不相逢
    2021-01-13 00:14

    It's not as simple as a type conversion.

    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__ has no idea how to handle a float:

    >>> (10).__eq__(10.0)
    NotImplemented
    

    but float.__eq__ knows how to handle ints:

    >>> (10.0).__eq__(10)
    True
    

    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 <=.)

提交回复
热议问题