Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multiplicity for user defined classes

Tags:

python

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 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])?

like image 275
oadams Avatar asked Jun 19 '26 14:06

oadams


1 Answers

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
like image 101
MAK Avatar answered Jun 22 '26 05:06

MAK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!