まあ、から十分に奇妙な結果を返すことによって、ブール値の論理的等価性と「ファジー」類似性の両方を意味するようにオーバーライドできます。__eq__
__eq__
class FuzzyBool(object):
def __init__(self, quality, tolerance=0):
self.quality, self._tolerance = quality, tolerance
def __nonzero__(self):
return self.quality <= self._tolerance
def tolerance(self, tolerance):
return FuzzyBool(self.quality, tolerance)
def __repr__(self):
return "sorta %s" % bool(self)
class ComparesFuzzy(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return FuzzyBool(abs(self.value - other.value))
def __hash__(self):
return hash((ComparesFuzzy, self.value))
>>> a = ComparesFuzzy(1)
>>> b = ComparesFuzzy(2)
>>> a == b
sorta False
>>> (a == b).tolerance(3)
sorta True
コンパレーターのデフォルトの動作は、比較された値が正確に等しい場合にのみ Truthy である必要があるため、通常の同等性は影響を受けません。