python指针和列表中用户定义对象的内存空间

时间:2013-06-04 19:26:55

标签: python list pointers

我希望有人能快速解决我遇到的这个问题。 我希望能够计算迭代中用户定义对象的出现次数。问题在于,当我创建一个对象来比较对象时,它会在内存空间中创建另一个对象,这样对象就不会被计算在内。

示例:

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

返回:

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>

有没有办法让列表的count方法适用于此实例,而无需在列表中为每个项目命名并调用其中的每个对象等等?

1 个答案:

答案 0 :(得分: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

有关详细信息,请参阅the documentation。请注意,如果您希望对象可以清洗(即可用作字典键),则必须多做一些。