所以我有这个课:
import yaml
class Config():
def __init__(self, filename):
self.config_filename=filename
def __read_config_file(self):
with open(self.config_filename) as f:
self.cfg = yaml.safe_load(f)
def get(self):
self.__read_config_file()
return self.cfg
而且效果很好。其背后的想法是,每次我在配置中使用某些内容时,都强制重新读取配置文件。这是用法示例:
cfg = Config('myconfig.yaml')
for name in cfg.get()['persons']:
print (cfg.get()['persons'][name]['phone'])
print (cfg.get()['persons'][name]['address'])
这有效,但我认为它看起来非常难看。我可以做这样的事情:
c = cfg.get()['persons']
for name in c:
print (c['persons'][name]['phone'])
print (c['persons'][name]['address'])
这看起来好一点,但是我也失去了重新加载访问权限的好处,但是我想做的是这样的事情(显然不起作用:]
for name in c:
print (name['phone'])
print (name['address'])
似乎对于迭代字典不了解,但是我主要的担心是,每次使用该文件中的任何值时,我都想重新加载配置文件,并且我希望它以一种易于阅读的方式。那么我该如何重新设计呢?
配置文件示例。如果需要,可以在此处更改格式。
persons:
john:
address: "street A"
phone: "123"
george:
address: "street B"
phone: "456"
因为它是一个元组,所以正常的迭代无效。我们可以通过以下方法遍历字典,
for name, person in c.items():
print(name)
print(person['phone'])
print(person['address'])
希望这会有所帮助