1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Map(dict): """ 提供字典的dot访问模式 Example: m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer']) m.first_name='Eduardo' """
def __init__(self, *args, **kwargs): super(Map, self).__init__(*args, **kwargs) for arg in args: if isinstance(arg, dict): for k, v in arg.items(): if isinstance(v, dict): v = Map(v) self[k] = v if kwargs: for k, v in kwargs.items(): if isinstance(v, dict): v = Map(v) self[k] = v
def __getattr__(self, attr): return self[attr]
def __setattr__(self, key, value): self.__setitem__(key, value)
def __getitem__(self, key): if key not in self.__dict__: super(Map, self).__setitem__(key, {}) self.__dict__.update({key: Map()}) return self.__dict__[key]
def __setitem__(self, key, value): super(Map, self).__setitem__(key, value) self.__dict__.update({key: value})
def __delattr__(self, item): self.__delitem__(item)
def __delitem__(self, key): super(Map, self).__delitem__(key) del self.__dict__[key]
|