2

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?

1 Answer 1

9

This looks wrong:

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

Maybe you meant:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.