这是我的数据结构......不要判断,使用风险自负:P
class KeyedDictionaryReturn(object):
def __init__(self, a, r):
self.exact = a
self.all = r
def __str__(self):
if self.exact: return str(self.exact)
class KeyedDictionary(dict):
def __init__(self, *args, **kwargs):
super(KeyedDictionary, self).__init__(*args, **kwargs)
def __getitem__(self, key):
_ret, _abs = [], None
for keys, values in self.items():
if isinstance(keys, tuple) and key in keys:
_ret.append(dict.__getitem__(self, keys))
elif isinstance(key, type(keys)) and key == keys:
_abs = dict.__getitem__(self, key)
_ret.append(_abs)
if len(_ret) == 0:
return None
if len(_ret) == 1:
return _ret[0]
return KeyedDictionaryReturn(_abs, _ret)
简单用法:
>>> k = KeyedDictionary()
>>> k.update({(1, 'one'):1})
>>> print(k)
>>> print(k[1])
>>> print(k['one'])
{(1, 'one'): 1}
1
1
>>> k.update({2:2})
>>> k.update({(2, 'two'):3})
>>> print(k)
>>> print(k[2])
>>> print(k[2].exact)
>>> print(k[2].all)
{(1, 'one'): 1, 2: 2, (2, 'two'): 3}
2
2
[2, 3]
...我不知道这是否是您想要的,或者这是否可以在没有 hack 的情况下在 memcache 中工作。