# 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
也可以返回对象本身。使用python>;=2.4:
^{pr2}$我想这会管用。。。在
这样做的好处是它只需要像其他一些解决方案建议的那样在列表中查找一次(而不是两次)。而且,许多人认为“请求原谅”比“先看后跳”更像Python。(EAFP与LBYL)
假设这两个对象是清单的一部分,而您只需要每个对象的一个实例,这两个对象可能被认为是相同的,但有其他不同的属性,因此您想重新查找已经没有新对象的对象
不过,你在这里所做的不会达到这个目的。你在一个列表中寻找一个对象的存在,然后返回相同的对象。它们不能有不同的属性,因为你在测试同一性和不相等性。在
最好将
list_of_objects
替换为dict_of_objects
,并根据对象的ID或名称进行查找:因此,检查列表中是否存在将始终返回与匹配项相同的项,而在字典中比较键可以检索到不同的项。在
相关问题 更多 >
编程相关推荐