1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python2: Why does the int class not have rich comparison operators like `__lt__()`?

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    Mostly curious.

    I've noticed (at least in py 2.6 and 2.7) that a float has all the familiar rich comparison functions: __lt__(), __gt__, __eq__, etc.

    >>> (5.0).__gt__(4.5)
    True


    but an int does not

    >>> (5).__gt__(4)
    Traceback (most recent call last):
    File "<input>", line 1, in <module>
    AttributeError: 'int' object has no attribute '__gt__'


    Which is odd to me, because the operator itself works fine

    >>> 5 > 4
    True


    Even strings support the comparison functions

    >>> "hat".__gt__("ace")
    True


    but all the int has is __cmp__()

    Seems strange to me, and so I was wondering why this came to be.

    Just tested and it works as expected in python 3, so I am assuming some legacy reasons. Still would like to hear a proper explanation though ;)

    Continue reading...

Compartilhe esta Página