Python data structure for a collection of objects with random access based on an attribute

后端 未结 4 1755
臣服心动
臣服心动 2021-02-06 15:31

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

4条回答
  •  死守一世寂寞
    2021-02-06 15:39

    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.

提交回复
热议问题