如何加载 pyYAML 文件并使用属性而不是使用字典符号访问它? [英] How to load a pyYAML file and access it using attributes instead of using the dictionary notation?
本文介绍了如何加载 pyYAML 文件并使用属性而不是使用字典符号访问它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 YAML 配置,如下所示:
配置:- id: foo- 名称:酒吧内容:- 运行:xxx- 删除:yyy
我正在使用 Python YAML 模块来加载它,但我想以更好的方式访问它,例如:
stream = open(filename)配置 = 加载(流,加载器 = 加载器)打印(配置['内容'])
我想要的是能够做到:print(config.content)
.
解决方案
您可以使用以下类在字典中使用对象表示法,如 这个答案:
class DictAsMember(dict):def __getattr__(self, name):价值=自我[名称]如果是实例(值,字典):值 = DictAsMember(value)返回值
这个类在行动:
<预><代码>>>>my_dict = DictAsMember(一=1, 二=2)>>>我的字典{'二':2,'一':1}>>>my_dict.two2编辑这对子字典递归起作用,例如:
<预><代码>>>>my_dict = DictAsMember(one=1, two=2, subdict=dict(three=3,four=4))>>>my_dict.one1>>>my_dict.subdict{'四':4,'三':3}>>>my_dict.subdict.four4I have an YAML config that looks like:
config:
- id: foo
- name: bar
content:
- run: xxx
- remove: yyy
I am using Python YAML module to load it but I want to access it in better ways like:
stream = open(filename)
config = load(stream, Loader=Loader)
print(config['content'])
What I want is to be able to do: print(config.content)
.
解决方案
You can use object notation with dictionaries using the following class, as discussed in this answer:
class DictAsMember(dict):
def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = DictAsMember(value)
return value
This class in action:
>>> my_dict = DictAsMember(one=1, two=2)
>>> my_dict
{'two': 2, 'one': 1}
>>> my_dict.two
2
Edit This works recursively with sub-dictionaries, for example:
>>> 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
这篇关于如何加载 pyYAML 文件并使用属性而不是使用字典符号访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文