Why/When in Python does `x==y` call `y.__eq__(x)`?

前端 未结 4 908
误落风尘
误落风尘 2020-12-05 02:12

The Python docs clearly state that x==y calls x.__eq__(y). However it seems that under many circumstances, the opposite is true. Where is it docu

4条回答
  •  感动是毒
    2020-12-05 03:00

    You're missing a key exception to the usual behaviour: when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first.

    See the documentation at:

    http://docs.python.org/reference/datamodel.html#coercion-rules

    and in particular, the following two paragraphs:

    For objects x and y, first x.__op__(y) is tried. If this is not implemented or returns NotImplemented, y.__rop__(x) is tried. If this is also not implemented or returns NotImplemented, a TypeError exception is raised. But see the following exception:

    Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class and overrides the base’s __rop__() method, the right operand’s __rop__() method is tried before the left operand’s __op__() method.

提交回复
热议问题