Dotsdict類實現(xiàn)了類似屬性訪問的方式訪問字典富寿。其繼承dict類月而,默認(rèn)支持輸入字典和關(guān)鍵字參數(shù)進(jìn)行初始化,可以遞歸地用點訪問珠漂、設(shè)置以及刪除字典的鍵值對。
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# Author: Xingbang Jiang
# E-mail: 1278561590@qq.com
# HomePage: http://wwww.xingbangsharing.tech
import re
class Dotsdict(dict):
def __init__(self, args, **kwargs):
super(Dotsdict, self).__init__(args, **kwargs)
for obj in [args, kwargs]:
for k, v in obj.items():
if isinstance(v, dict):
v = Dotsdict(v)
self.__setitem__(k, v)
def __setitem__(self, key, val):
super(Dotsdict, self).__setitem__(key, val)
# self.__dict__[key] = val
def __delitem__(self, key):
super(Dotsdict, self).__delitem__(key)
# del self.__dict__[key]
def __getitem__(self, key):
return super(Dotsdict, self).__getitem__(key)
def __missing__(self, key):
dots = Dotsdict()
self.__setitem__(key, dots)
return dots
__setattr__, __delattr__, __getattr__ = __setitem__, __delitem__, __getitem__