I need a collection of objects which can be looked up by a certain (unique) attribute common to each of the objects. Right now I am using a dicitionary assigning the dictionary
There are a number of great things you can do here. One example would be to let the class keep track of everything:
class Item():
_member_dict = {}
@classmethod
def get_by_key(cls,key):
return cls._member_dict[key]
def __init__(self, uniq_key, title=None):
self.key = uniq_key
self.__class__._member_dict[key] = self
self.title = title
>>> i = Item('foo')
>>> i == Item.get_by_key('foo')
True
Note you will retain the update problem: if key
changes, the _member_dict
falls out of sync. This is where encapsulation will come in handy: make it (practically) impossible to change key
without updating the dictionary. For a good tutorial on how to do that, see this tutorial.