[英]Best way to implement multiple types of equality checks in python
假設我有一個Person類,具有名字,中間名和姓氏屬性。 我希望能夠對Person對象執行兩種不同類型的相等性檢查:
我一直在__ne__
分別為此使用__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
最小驚訝的原理:使不精確匹配成為一種命名方法,而不是重載運算符。 對於完全匹配,可以重載==
可以,但是用非顯而易見的語義重載運算符可能會造成混亂。 Person("G. Bluth").could_be(Person("George Oscar Bluth"))
輸入幾個字符並寫Person("G. Bluth").could_be(Person("George Oscar Bluth"))
嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.