<p>假设这两个对象是清单的一部分,而您只需要每个对象的一个实例,这两个对象可能被认为是相同的,但有其他不同的属性,因此您想重新查找已经没有新对象的对象</p>
<p>不过,你在这里所做的不会达到这个目的。你在一个列表中寻找一个对象的存在,然后返回相同的对象。<em>它们不能有不同的属性,因为你在测试同一性和不相等性。在</p>
<p>最好将<code>list_of_objects</code>替换为<code>dict_of_objects</code>,并根据对象的ID或名称进行查找:</p>
<pre><code># Example class with identifier
class ExampleObject(object):
def __init__(self, name):
self.name = name
example1 = ExampleObject('one')
# Object Registry: just convenience methods on a dict for easier lookup
class ObjectRegistry(dict):
def register(self, object):
self[object.name] = object
def lookup(self, object):
name = getattr(object, 'name', object)
return self.get(name, object)
# Create the registry and add some objects
dict_of_objects = ObjectRegistry()
dict_of_objects.register(example1)
# Looking up the existing object will return itself
assert dict_of_objects.lookup(example1) is example1
# Looking up a new object with the same name will return the original
example1too = ExampleObject('one')
assert dict_of_objects.lookup(example1too) is example1
</code></pre>
<p>因此,检查列表中是否存在将始终返回与匹配项相同的项,而在字典中比较键可以检索到不同的项。在</p>