Pythonic 从配置文件中读取
我有一个 python 类,它使用 ConfigParser 读取配置文件:
配置文件:
[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')
我觉得最后四行是重复的,应该以某种方式压缩为一个 Pythonic 行,该行将创建一个 self.item该部分中每个项目的 code> 变量。
有什么想法吗?
Adam
更新:
根据您的回答,我已将代码修改为:
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}
I have a python class which reads a config file using ConfigParser:
Config file:
[geography]
Xmin=6.6
Xmax=18.6
Ymin=36.6
YMax=47.1
Python code:
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')
I feel that the last four lines are repetitive, and should somehow be compressed to one Pythonic line that would create a self.item
variable for each item in the section.
Any ideas?
Adam
UPDATE:
Following your answers, I've modified my code to:
for item in config.items('geography'):
setattr(self, '_'+item[0], float(item[1]))
Now,
print self.__dict__
>>> {'_xmax': 18.600000000000001, '_ymax': 47.100000000000001,
'_ymin': 36.600000000000001, '_xmin': 6.5999999999999996}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常尝试避免构造函数中的外部交互 - 这使得测试代码变得困难。最好传递配置解析器实例或类似 fp 的对象而不是文件名。
I usually try to avoid external interactions in a constructor - makes it hard to test the code. Better pass a config parser instance or a fp-like object instead of a filename.
怎么样:
请注意,上面的代码会将其分配给 self.xmin 而不是 self.x_min...但是,如果您对此命名没问题,那么这应该可以...否则,名称之间的映射将需要更多代码比原来的。
How about something like:
Note that the above will assign it to self.xmin instead of self.x_min... however, if you are fine with that naming, then this should work... otherwise, mapping between names would be more code than the original.