Ada*_*tan 2 python coding-style dry configparser
我有一个python类,它使用ConfigParser读取配置文件:
配置文件:
[geography]
Xmin=6.6
Xmax=18.6
Ymin=36.6
YMax=47.1
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
我觉得最后四行是重复的,并且应该以某种方式压缩到一个Pythonic线,这将self.item为该部分中的每个项创建一个变量.
有任何想法吗?
亚当
更新:
根据您的回答,我已将我的代码修改为:
for item in config.items('geography'):
setattr(self, '_'+item[0], float(item[1]))
Run Code Online (Sandbox Code Playgroud)
现在,
print self.__dict__
>>> {'_xmax': 18.600000000000001, '_ymax': 47.100000000000001,
'_ymin': 36.600000000000001, '_xmin': 6.5999999999999996}
Run Code Online (Sandbox Code Playgroud)
我通常会尝试避免构造函数中的外部交互 - 使代码测试变得困难.更好地传递配置解析器实例或类似fp的对象而不是文件名.