ConfigParserを使用して構成ファイルを読み取るPythonクラスがあります。
構成ファイル:
[geography]
Xmin=6.6
Xmax=18.6
Ymin=36.6
YMax=47.1
Pythonコード:
class Slicer:
def __init__(self, config_file_name):
config = ConfigParser.ConfigParser()
config.read(config_file_name)
# Rad the lines from the file
self.x_min = config.getfloat('geography', 'xmin')
self.x_max = config.getfloat('geography', 'xmax')
self.y_min = config.getfloat('geography', 'ymin')
self.y_max = config.getfloat('geography', 'ymax')
self.item
最後の4行は繰り返しであり、セクション内の各項目の変数を作成する1つのPythonic行に何らかの形で圧縮する必要があると思います。
何か案は?
アダム
アップデート:
あなたの答えに従って、私は私のコードを次のように変更しました:
for item in config.items('geography'):
setattr(self, '_'+item[0], float(item[1]))
今、
print self.__dict__
>>> {'_xmax': 18.600000000000001, '_ymax': 47.100000000000001,
'_ymin': 36.600000000000001, '_xmin': 6.5999999999999996}