mirror of
https://github.com/python/cpython.git
synced 2025-09-28 11:15:17 +00:00
Update the sorting howto to reflect the PEP 8 advisory to define all six rich comparisons.
This commit is contained in:
parent
cfe6deb6f7
commit
c766b31dbc
1 changed files with 7 additions and 3 deletions
|
@ -276,11 +276,15 @@ Odd and Ends
|
||||||
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
|
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
|
||||||
>>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data))))
|
>>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data))))
|
||||||
|
|
||||||
* The sort routines are guaranteed to use :meth:`__lt__` when making comparisons
|
* To create a standard sort order for a class, just add the appropriate rich
|
||||||
between two objects. So, it is easy to add a standard sort order to a class by
|
comparison methods:
|
||||||
defining an :meth:`__lt__` method::
|
|
||||||
|
|
||||||
|
>>> Student.__eq__ = lambda self, other: self.age == other.age
|
||||||
|
>>> Student.__ne__ = lambda self, other: self.age != other.age
|
||||||
>>> Student.__lt__ = lambda self, other: self.age < other.age
|
>>> Student.__lt__ = lambda self, other: self.age < other.age
|
||||||
|
>>> Student.__le__ = lambda self, other: self.age <= other.age
|
||||||
|
>>> Student.__gt__ = lambda self, other: self.age > other.age
|
||||||
|
>>> Student.__ge__ = lambda self, other: self.age >= other.age
|
||||||
>>> sorted(student_objects)
|
>>> sorted(student_objects)
|
||||||
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
|
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue