我希望有人能快速解决我遇到的这个问题。我希望能够计算用户定义的对象在迭代器中出现的次数。问题是,当我创建一个对象与之进行比较时,它会在内存空间中创建另一个对象,这样该对象就不会在应该计数的时候被计算在内。
示例:
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>有没有一种方法可以让list的count方法在这个实例上工作,而不必在放入list时命名列表中的每一项,并调用每个引用对象,等等?
发布于 2013-06-05 03:28:12
您需要为您的类定义一个__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。注意,如果你想要你的对象是hashable的(例如,可以作为字典的键),你需要做更多的事情。
https://stackoverflow.com/questions/16925899
复制相似问题