Comparison operators vs “rich comparison” methods in Python

前端 未结 2 1587
广开言路
广开言路 2021-02-05 15:11

Can someone explain me the differences between the two. Are those normally equivalent ? Maybe I\'m completely wrong here, but I thought that each comparison operator was necessa

2条回答
  •  Happy的楠姐
    2021-02-05 15:42

    Note for operator < versus __lt__:

    import types
    
    class A:
        def __lt__(self, other): return True
    
    def new_lt(self, other): return False
    
    a = A()
    print(a < a, a.__lt__(a))  # True True
    a.__lt__ = types.MethodType(new_lt, a)
    print(a < a, a.__lt__(a))  # True False
    A.__lt__ = types.MethodType(new_lt, A)
    print(a < a, a.__lt__(a))  # False False
    

    < calls __lt__ defined on class; __lt__ calls __lt__ defined on object.

    It's usually the same :) And it is totally delicious to use: A.__lt__ = new_lt

提交回复
热议问题