'Reversed' comparison operator in Python

前端 未结 1 998
萌比男神i
萌比男神i 2021-01-18 09:49
class Inner():

    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        if isinstance(other, Inner):
            return self.x == other.x         


        
相关标签:
1条回答
  • 2021-01-18 10:05

    Not to put too fine a point on it: Inner.__eq__ is broken. At the very least, rather than throwing an error it should return NotImplemented, which would allow Python to try the reverse comparison:

    When NotImplemented is returned, the interpreter will then try the reflected operation on the other type, or some other fallback, depending on the operator. If all attempted operations return NotImplemented, the interpreter will raise an appropriate exception.

    Better yet it would use "duck typing", rather than insisting on a specific class (unless the class, rather than its interface, is an explicitly important part of the comparison):

    def __eq__(self, other):
        try:
            return self.x == other.x
        except AttributeError:
            return NotImplemented
    

    However, as you say you cannot control this, you will have to manually implement similar functionality, for example:

    def compare(a, b):
        """'Safe' comparison between two objects."""
        try:
            return a == b
        except TypeError:
            return b == a
    

    as there is no such thing as __req__ in Python's data model.

    0 讨论(0)
提交回复
热议问题