mypy: Why is “int” a subtype of “float”?

前端 未结 2 1143
慢半拍i
慢半拍i 2020-12-16 19:43

Why does \"mypy\" consider \"int\" as a subtype of \"float\"? A subtype shall support all methods of its supertype, but \"float\" has methods, which \"int\" does not support

2条回答
  •  难免孤独
    2020-12-16 20:30

    As @juanpa.arrivillaga pointed out, the explanation is on https://mypy.readthedocs.io/en/latest/duck_type_compatibility.html.

    A subtype shall support all methods of its supertype, but "float" has methods, which "int" does not support

    int is not a subtype of float, so it doesn't have to support methods of float.

    The mechanism is good because passing integer values shouldn't cause errors, unless you really want them as in your example. You explicitly tried to use a method which doesn't exist. In common situations, we only make arithmetic operations on numbers, so a problem rarely exists and you can always avoid it by adding .0 as you wrote.

    It is a common behavior in most languages to assume that int is a special case of float, consider for example C++ int to float implicit conversion.

提交回复
热议问题