chase
chase

Reputation: 3782

python pointers and memory space of user defined objects in lists

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?

Upvotes: 0

Views: 107

Answers (1)

BrenBarn
BrenBarn

Reputation: 251353

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).

Upvotes: 3

Related Questions