在python中实现多种类型的相等性检查的最佳方法

时间:2013-06-20 17:08:31

标签: python oop equality

假设我有一个Person类,具有first,middle和last name属性。我希望能够对Person对象执行两种不同类型的相等性检查:

  • 基于所有属性的字符串比较完全相同
  • 不矛盾,即“G. Bluth”==“George Oscar Bluth”

我一直在考虑分别使用__eq____ne__的想法:

Person('g', '', 'bluth') == Person('george', 'oscar', 'bluth')  # False
Person('g', '', 'bluth') != Person('george', 'oscar', 'bluth')  # False

这似乎是一个简洁的解决方案,但!=并不总是返回==的反面,但让我感到紧张。这被认为是不好的做法吗?我应该避免使用运算符,只使用像consistent(self, other)这样的方法吗?

示例实施:

class Person(object):
    def __init__(self, first, middle, last):
        self.first = first
        self.middle = middle
        self.last = last
    def __eq__(self, other):
        if type(other) is type(self):
            return self.__dict__ == other.__dict__
        return NotImplemented
    def __ne__(self, other):
        if type(other) is type(self):
            return not (self._compatible(self.first, other.first) and 
                        self._compatible(self.middle, other.middle) and 
                        self._compatible(self.last, other.last))
        return NotImplemented
    def _compatible(self, s, o):
        if s and o:
            if s == o or (len(s) == 1 and s == o[0]) or (len(o) == 1 and o == s[0]):
                return True
            return False
        return True

1 个答案:

答案 0 :(得分:5)

最小惊讶原则:使不精确匹配成为命名方法,而不是重载运算符。重载==以获得完全匹配是可以的,但是使用除明显之外的语义重载运算符可能会导致混淆。是否非常难以输入更多字符并编写Person("G. Bluth").could_be(Person("George Oscar Bluth"))