Kurisu
Kurisu

Reputation: 852

How do I make a class in Python behave with Sets?

I have a class.

class Part:
    def __init__(self,name):
        self.name = name
        self.count = 0
    def __hash__(self):
        return hash(self.name)
    def __lt__(self,other):
        return self.count < other.count
    def __eq__(self,other):
        return self.name == self.count

I create a bunch of these objects, and populate a list with them. This list ends up containing duplicates. I need that for one segment in my code, but when it comes time to output, I want to only output each part once. So I stick it in a Set.

uniqueParts = set(parts)

I then Iterate over this to write it to file.

for part in uniqueParts:
    f.write(part.name+": "+str(part.count)+'\n')

This does not work. It outputs every duplicate. Since uniqueParts is a set, it must be something wrong with my class where the Set can't tell that they are duplicates.

Now, I can solve my specific problem several different ways (re-write the class so I don't need it (data is probably too simple to deserve it's own class) or iterate through and delete the duplicates, or rework my code so duplicates never occur in the first place) But I will probably run into this problem again in the future, and I'd like to know what I need to do to get Sets to work with classes I've written myself.

Thoughts/Assistance?

Upvotes: 2

Views: 117

Answers (1)

Emil Ivanov
Emil Ivanov

Reputation: 37633

This looks wrong:

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

Maybe you meant:

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

Upvotes: 9

Related Questions