这是一种将多个字典链接在一起的方法(一个具有默认值,另一个具有更新的假设):
import UserDict
class Chainmap(UserDict.DictMixin):
"""Combine multiple mappings for successive lookups.
For example, to emulate Python's normal lookup sequence:
import __builtin__
pylookup = Chainmap(locals(), globals(), vars(__builtin__))
"""
def __init__(self, *maps):
self._maps = maps
def __getitem__(self, key):
for mapping in self._maps:
try:
return mapping[key]
except KeyError:
pass
raise KeyError(key)
def keys(self):
result = []
seen = set()
for mapping in self_maps:
for key in mapping:
if key not in seen:
result.append(key)
seen.add(key)
return result
更完整的字典接口见 init.py#l754">http://hg.python.org/cpython/file/ab5d39caad6f/Lib/collections/init .py# l754
ChainMap类可以这样使用:
base_assumptions = dict(a1=10, a2=15, a3=30)
class FundClass:
def __init__(self, fund, investor_assumptions) #dict to be unpacked via '**' when passed
combined_dict = ChainMap(investor_assumptions, base_assumptions)
self.some_var = combined_dict['a1']