我有一个 YAML 配置,如下所示:
config:
- id: foo
- name: bar
content:
- run: xxx
- remove: yyy
我正在使用 Python YAML 模块来加载它,但我想以更好的方式访问它,例如:
stream = open(filename)
config = load(stream, Loader=Loader)
print(config['content'])
我想要的是能够做到:print(config.content)
。
最佳答案
您可以使用以下类在字典中使用对象表示法,如 this 中所述回答:
class DictAsMember(dict):
def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = DictAsMember(value)
return value
这个类在行动:
>>> my_dict = DictAsMember(one=1, two=2)
>>> my_dict
{'two': 2, 'one': 1}
>>> my_dict.two
2
编辑 这对子词典递归地起作用,例如:
>>> my_dict = DictAsMember(one=1, two=2, subdict=dict(three=3, four=4))
>>> my_dict.one
1
>>> my_dict.subdict
{'four': 4, 'three': 3}
>>> my_dict.subdict.four
4
关于python - 如何加载 pyYAML 文件并使用属性而不是使用字典符号访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11049117/