python total_ordering : why __lt__ and __eq__ instead of __le__?

左心房为你撑大大i 提交于 2020-12-29 05:19:05

问题


In Python3, the functools.total_ordering decorator allows one to only overload __lt__ and __eq__ to get all 6 comparison operators.

I don't get why one has to write two operators when one would be enough, namely __le__ or __ge__, and all others would be defined accordingly :

a < b   <=>   not (b <= a)
a > b   <=>   not (a <= b)
a == b   <=>   (a <= b) and (b <= a)
a != b   <=>   (a <= b) xor (b <= a)

Is that just because xor operator does not exists natively?


回答1:


The documentation states you must define one of __lt__(), __le__(), __gt__(), or __ge__(), but only should supply an __eq__() method.

In other words, the __eq__ method is optional.

The total_ordering implementation does not require you to specify an __eq__ method; it only tests for the __lt__(), __le__(), __gt__(), or __ge__() methods. It supplies up to 3 missing special methods based of one of those 4.

The __eq__ method is optional because the base object object defines one for you; two instances are considered equal only if they are the same object; ob1 == ob2 only if ob1 is ob2 is True. See the do_richcompare() function in object.c; remember that the == operator in the code there is comparing pointers.



来源:https://stackoverflow.com/questions/16238322/python-total-ordering-why-lt-and-eq-instead-of-le

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!