Python __多类型散列的eq_uuu实现
我有一个自定义类,我希望能够将其用作字典中的键。因此,我需要定义Python __多类型散列的eq_uuu实现,python,dictionary,hash,Python,Dictionary,Hash,我有一个自定义类,我希望能够将其用作字典中的键。因此,我需要定义\uuuu eq\uuu函数。就我而言,这很简单: def __eq__(self, other): return self.name == other.name 这里的other需要基本上是相同的类型,我正在比较一些成员变量。但是,名称只是一个字符串,我想用户也可以通过指定字符串进行检查。具体来说,以下是我的想法: class Hashable(object): def __init__(self
\uuuu eq\uuu
函数。就我而言,这很简单:
def __eq__(self, other):
return self.name == other.name
这里的other
需要基本上是相同的类型,我正在比较一些成员变量。但是,名称
只是一个字符串,我想用户也可以通过指定字符串进行检查。具体来说,以下是我的想法:
class Hashable(object):
def __init__(self, name):
self.name = name
self.other_att = dict()
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
# Example usage
from collections import defaultdict
c = defaultdict()
h = Hashable("Name")
c[h] = list()
if h in c:
print ("Yes!") # This is fine...
但是,我们也要做:
if 'Name' in c:
我是否可以实现许多
\uuuu eq\uuu
函数,或者我是否需要检查相等函数中的其他
类型。什么是蟒蛇式的方法是最有效的方法?你可以使用尝试一下,除了,因为有时候请求原谅比请求允许更容易:
def __eq__(self, other):
try:
return self.name == other.name
except AttributeError:
return self.name == other
您可以使用尝试,但不使用,因为有时候请求原谅比请求允许更容易:
def __eq__(self, other):
try:
return self.name == other.name
except AttributeError:
return self.name == other
如果other
没有属性name
,则使用并提供默认值作为other
,例如,它是一个字符串:
def __eq__(self, other):
return self.name == getattr(other, 'name', other)
如果other
没有属性name
,则使用并提供默认值作为other
,例如,它是一个字符串:
def __eq__(self, other):
return self.name == getattr(other, 'name', other)
听起来您可能只想将名称作为键,并使对象的名称来自于值的一部分。另外:不要忘记实现\uuuu ne\uuuu
,因为Python 2上没有为您提供它,请记住,您应该正式返回NotImplemented
,以便与您的类型不处理的对象进行比较,而不是提出AttributeError
或返回False
(以便让对方有机会定义比较的含义)。听起来您可能只想将名称作为键,并使对象的名称来自于值的一部分。另外:不要忘记实现\uu________
,因为Python 2上没有为您提供它,请记住,您正式应该返回NotImplemented
,以便与您的类型不处理的对象进行比较,而不是提出AttributeError
或返回False
(以便让另一方有机会定义比较的含义)。