定义配置文件并使用ConfigParser解析它来定义一堆对象初始值(也就是:构造函数值)的最佳方法是什么
示例:
[Person-Objects]
Name: X
Age: 12
Profession: Student
Address: 555 Tortoise Drive
Name: Y
Age: 29
Profession: Programmer
Address: The moon
然后能够用Python解析它,所以我可以有类似的东西:
People = []
for person in config:
People.append(person)
Person1 = People[0]
print Person1.Profession # Prints Student
答案 0 :(得分:2)
您可以执行以下操作:
[person:X]
Age: 12
Profession: Student
Address: 555 Tortoise Drive
[person:Y]
Age: 29
Profession: Programmer
Address: The moon
然后在你的代码中:
config = ConfigParser()
config.read('people.ini')
people = []
for s in config.sections():
if not s.startswith('person:'):
continue
name = s[7:]
person = dict(config.items(s))
person['name'] = name
people.append(person)