开发者

Set multiplicity for user defined classes

I want to use sets on some classes I've made. I want those sets to restrict the multiplicity of my objects of that class. However I have a problem. Consider this toy example:

class Thing(object):

    def __init__(self, value):
        self.value = value

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

    def __repr__(self):
        return str(self.value)

a = Thing(5)
b = Thing(5)

s = set()
s.add(a)
s.add(b)
print s

The output of 开发者_StackOverflow中文版this code is:

set([5, 5])

I just assumed that set() would use __eq__ to determine whether the object should be included, but perhaps it uses is. Is there an easy workaround such that the output would just be set([5])?


You need to define the __hash__ method of your class to return a hashcode based on value. In other words, you need to make your class hashable.

class Thing(object):

    def __init__(self, value):
        self.value = value

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

    def __repr__(self):
        return str(self.value)

    def __hash__(self):
        return hash(self.value)

a = Thing(5)
b = Thing(5)

s = set()
s.add(a)
s.add(b)
print s
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜