Why Python said in __lt __, __ gt__ as the "rich comparison" methods

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

In Python base class object to provide a series of objects that can be used to achieve the same "comparative" method can be used for different objects of the same instance is compared, including __lt__、__gt__、__le__、__ge__、__eq__和__ne__six methods.
So why is it called "rich comparison" ( "rich comparison") way to do that? Check the relevant information, and did not see the authoritative definition, old ape combined with sporadic online data, analysis for the following reasons:

  1. Python2.1 previous comparative method provides only a __cmp__ method, there is no method __lt__ six other relatively __cmp__ a method, the current ratio of the wide variety of methods, Python 2.1 introduces a rich comparison method, Python3.4 void after __cmp__ method;
  2. Comparison of methods other than simple magnitude comparison, also can be used for sorting, from the beginning Python2.4, sorted sort () function, and sorted () adds both a 'key' parameter to specify each before making comparisons function on the element to be called, the return value of this function is that as long as the old ape any comparison of the data type (including the custom class defines __lt__ method) can be, that the return value than mere __cmp__ It returns three values ​​(0,1, -1) richer range;
  3. For comparison supports complex class method calls corresponding to each comparator comparing a separate rich __cmp__ method without a common method, whereby a ratio __cmp__ To consider the different situations achieve simple, efficient runtime performance;
  4. Rich comparison method can be directly mapped to the corresponding operator such as "<", the operation is more convenient and simple.
    The above analysis, I do not know whether the correct and complete, please take great advice.

About rich comparative method please refer to:
1, "Section 8.21 Python in __lt __, __ gt__ and other" relatively rich "(" rich comparison ") method to explore the use of"
2, "the first 8.22 Python Case Detailed: Rewrite "relatively rich" approach control comparator logic " .

Old ape Python, with the old ape learn Python!
Blog address: https: //blog.csdn.net/LaoYuanPython

please support, thumbs up, comment and processing concern! Thank you!

Guess you like

Origin blog.csdn.net/LaoYuanPython/article/details/95082169