下面是嵌套属性字典的另一个实现(受 Curt Hagenlocher 的回答启发,精简为基本内容):
class AttrDict(dict):
""" Nested Attribute Dictionary
A class to convert a nested Dictionary into an object with key-values
accessible using attribute notation (AttrDict.attribute) in addition to
key notation (Dict["key"]). This class recursively sets Dicts to objects,
allowing you to recurse into nested dicts (like: AttrDict.attr.attr)
"""
def __init__(self, mapping=None):
super(AttrDict, self).__init__()
if mapping is not None:
for key, value in mapping.items():
self.__setitem__(key, value)
def __setitem__(self, key, value):
if isinstance(value, dict):
value = AttrDict(value)
super(AttrDict, self).__setitem__(key, value)
self.__dict__[key] = value # for code completion in editors
def __getattr__(self, item):
try:
return self.__getitem__(item)
except KeyError:
raise AttributeError(item)
__setattr__ = __setitem__
这适用于 Python 2 和 3:
life = AttrDict({'bigBang': {'stars': {'planets': {}}}})
life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {}}}
life.bigBang.stars.planets.earth.multiCellLife = {'reptiles': {}, 'mammals': {}}
print(life.bigBang.stars.planets.earth)
# -> {'singleCellLife': {}, 'multiCellLife': {'mammals': {}, 'reptiles': {}}}
__getattr__
在 Python3 中需要将 KeyError转换为 AttributeError ,这样在找不到hasattr
属性的情况下也可以使用:
hasattr(life, 'parallelUniverse')
# --> False