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

猜你喜欢

转载自blog.csdn.net/weixin_33881753/article/details/90867608
今日推荐