美文网首页
python字典转对象,通过点(.)调用

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

作者: stay丶gold | 来源:发表于2019-06-03 21:46 被阅读0次
# -*- 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字典转对象,通过点(.)调用

      本文链接:https://www.haomeiwen.com/subject/ewxjeqtx.html