from attrdict import AttrDict
test_dict = {
"key1": "value1",
"key2":{
"key2_1": "value2_1",
"key2_2": "value2_2"
},
"key3": [
{
"key3_1": "value3-1"
},
{
"key3_2": "value3-2"
}
]
}
ad = AttrDict(test_dict)
print(ad.key1) # value1
print(ad.key2) # AttrDict({'key2_1': 'value2_1', 'key2_2': 'value2_2'})
print(ad.key3) # (AttrDict({'key3-1': 'value3-1'}), AttrDict({'key3-2': 'value3-2'}))
print(ad.key2.key2_1) # value2_1
print(ad.key3[0].key3_1) # value3-1
# dict的key为违法变量时访问直接报错
ad1 = AttrDict({'9as': 'value3-2'})
print(getattr(ad1, "9as")) # AttributeError: 'AttrDict' instance has no attribute '9as'
# 源码如下
def __getattr__(self, key):
"""
Access an item as an attribute.
"""
if key not in self or not self._valid_name(key):
raise AttributeError(
"'{cls}' instance has no attribute '{name}'".format(
cls=self.__class__.__name__, name=key
)
)
return self._build(self[key])
01-12
2544
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-14
367
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-22
09-28
375
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交