2013-06-20 19 views
0

說我有一個Person類,具有名字,中間名和姓氏屬性。我希望能夠在Person對象執行兩種不同類型平等檢查:在Python中實現多種類型相等性檢查的最佳方式

  • 正好等於基於所有的字符串比較屬性
  • 不相矛盾,即「唐博濤G.」 ==「喬治·奧斯卡唐博濤」

我一直在玩弄使用__eq____ne__單獨爲這個的想法:

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

IT方面eems像一個整潔的解決方案,但有!=並不總是返回==的相反讓我感到緊張。它被認爲是不好的做法?我應該避開使用操作員,只使用像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

如果您的代碼將被您自己以外的任何人使用/查看/維護,我強烈建議不要以您提出的方式使用'!='。哎呀,即使不是,你稍後再回來查看它,你可能不會記得'!='有點不同。 – jedwards

回答

5

原理:使不完全匹配是命名法,而不是一個重載操作符。對於精確匹配而言,超載==是可以的,但重載運算符的語義不同於明顯的可能會導致混淆。輸入更多字符並寫入Person("G. Bluth").could_be(Person("George Oscar Bluth"))難度非常大嗎?

相關問題