2013-06-04 20 views
0

我希望有人对我遇到的这个问题有一个快速修复。 我希望能够在迭代中计数用户定义对象的出现次数。问题是,当我创建一个对象来比较对象时,它会在内存空间中创建另一个对象,以便该对象在应该出现时不会被计数。列表中的用户定义对象的Python指针和内存空间

例子:

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方法,而无需你把命名列表中的每个项目它在哪里召唤这些指称对象?

回答

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了解更多信息。请注意,如果您希望对象是可散列的(即可用作字典键),则必须多做一点。

+0

谢谢@BrenBarn,这非常有帮助。顺便说一下适当的姓。 – chase

+1

使它可哈希:'def __hash __(self):return hash((self.i,self.j))'它假定列表只包含'__eq__',列表只包含Barn对象。 – jfs

+0

如果一个Barn对象在其中包含可变数量的猫作为属性(整个程序中连续更改的猫的数量),该怎么办?这是否使谷仓变得可变,或者,因为它仍然是同一个谷仓,是否可以被散列呢? – chase

相关问题