所以我有这样的课程:
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"