0

I am hoping that someone has a quick fix to this problem I am having. I would like to be able to count the occurrences of a user defined object within an iterable. The problem is that when I create an object to compare the object to, it creates another object in the memory space, such that the object is not counted when it should be.

Example:

class Barn:
    def __init__(self, i,j):
        self.i = i
        self.j = j

barns = [Barn(1,2), Barn(3,4)]
a = Barn(1,2)
print 'number of Barn(1,2) is', barns.count(Barn(1,2))
print 'memory location of Barn(1,2) in list', barns[0]
print 'memory location of Barn(1,2) stored in "a"', a

returns:

number of Barn(1,2) is 0
memory location of Barn(1,2) in list <__main__.Barn instance at 0x01FCDFA8>
memory location of Barn(1,2) stored in "a" <__main__.Barn instance at 0x01FD0030>

is there a way to make the count method of a list work for this instance without having to name each item in the list as you put it in and call each of those referents, etc?

1 Answer 1

3

You need to define an __eq__ method for your class that defines what you want equality to mean.

class Barn(object):
    def __init__(self, i,j):
        self.i = i
        self.j = j
    def __eq__(self, other):
        return self.i == other.i and self.j == other.j

See the documentation for more info. Note that you'll have to do a bit more if you want your object to be hashable (i.e., usable as a dictionary key).

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @BrenBarn , that's very helpful. Appropriate last name by the way.
to make it hashable: def __hash__(self): return hash((self.i, self.j)) It assumes as well as __eq__ that the list contains only Barn objects.
what if a Barn object has a variable number of cats within it as a property (number of cats changed continuously throughout the program)? Does this make the Barn mutable, or, since it's still the same Barn, is that OK to be hashed as well?
@chase: If you want it to be hashable, the information you use to compute the hash can't change during the object's lifetime. So if you're going to make use of the cats in the hash, you can't change the number of cats after creating the object.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.