利用类的__dict__属性重新封装字典,注意这里__dict__只能读取字典的第一层的键,多层嵌套字典需要使用递归进行构建,如toDotDict函数

class DotDict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.__dict__ = self

    def toDotDict(data):
        if isinstance(data, dict):
            for k, v in data.items():
                if isinstance(v, dict):
                    data[k] = DotDict(v)
                    DotDict.toDotDict(data[k])
        else:
            return data

        return DotDict(data)

测试类,类中包含一个待操作的字典

class Test:
	Info = { "a": { "c" : 0}}
	def __init__(self):
		self.__dict__ = DotDict.toDotDict(self.Info)

使用语句,支持键以及点操作符读写字典相应键的对应值

if __name__ == "__main__":
    test = Test()
    print(test.a.c)
    print(test.__dict__["a"]["c"])
    test.a.c = "ccc"
    print(test.a.c)
    print(test.__dict__["a"]["c"])