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?

4

1 回答 1

3

您需要__eq__为您的类定义一个方法,该方法定义您想要相等的含义。

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

有关更多信息,请参阅文档。请注意,如果您希望您的对象是可散列的(即,可用作字典键),您将不得不做更多的事情。

于 2013-06-04T19:28:12.017 回答