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
如果您的代码将被您自己以外的任何人使用/查看/维护,我强烈建议不要以您提出的方式使用'!='。哎呀,即使不是,你稍后再回来查看它,你可能不会记得'!='有点不同。 – jedwards