python字典转对象,通过点(.)调用

# -*- coding: UTF-8 -*-
class Dict2Obj(dict):
    def __init__(self, *args, **kwargs):
        super(Dict2Obj, self).__init__(*args, **kwargs)

    def __getattr__(self, key):
        value = self[key]
        if isinstance(value, dict):
            value = Dict2Obj(value)
        return value


d = {"a": "b", "c": {"d": "e"}}
obj = Dict2Obj(d)
print(obj.a)
print(obj.c)
print(obj.c.d)

>>>b
>>>{'d': 'e'}
>>>e

你可能感兴趣的:(python字典转对象,通过点(.)调用)