turn python dictionary object, call by dot (.)

# -*- 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

Guess you like

Origin blog.csdn.net/weixin_33881753/article/details/90867608