__eq__实现多种类型的散列

时间:2017-04-22 16:49:43

标签: python dictionary hash

我有一个自定义类,我希望它可以用作字典中的键。所以,我需要定义__eq__函数。就我而言,这很简单:

    def __eq__(self, other):
        return self.name == other.name

这里other基本上需要基本相同,我比较一些成员变量。但是,name只是一个字符串,我想的是用户也可以通过指定字符串进行检查。为了使它具体化,这就是我的想法:

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:

我可以实现许多__eq__函数,还是需要在相等函​​数中检查other的类型。什么是pythonic是一种希望有效的方法呢?

2 个答案:

答案 0 :(得分:2)

您可以使用try-except,因为有时候请求宽恕比获得权限更容易:

def __eq__(self, other):
    try:
        return self.name == other.name
    except AttributeError:
        return self.name == other

答案 1 :(得分:2)

如果other没有属性other,请使用getattr并将默认设置为name。这是一个字符串:

def __eq__(self, other):
    return self.name == getattr(other, 'name', other)
相关问题