2 回答
TA贡献2041条经验 获得超4个赞
我认为此实现适合您的需求:
class Config(object):
def __getattr__(self, name):
if name in self.config:
return self.config[name]
else:
raise AttributeError("No parameter named [%s]" % name)
def __init__(self, file=None):
# changed to make it work without real file
self.config = {'key': 'value'}
config = Config()
print(config.key) # value
print(config.not_a_key) # AttributeError: ...
不需要写_ConfigStorage和__del__,没有无限递归,通过点表示法访问。
TA贡献1827条经验 获得超9个赞
愚蠢,但我找到了更优雅的方法来解决我的问题。
class Config(object):
config = dict()
def __getattribute__(self, name):
if name in Config.config:
return Config.config[name]
else:
raise AttributeError("No parameter named [%s]" % name)
def __init__(self, file):
try:
with open(file, 'r') as f:
for config_line in f:
config_line = config_line.strip()
eq_position = config_line.find('=')
key = config_line[:eq_position].strip()
value = config_line[eq_position + 1:].strip()
Config.config[key] = value
except FileNotFoundError:
print('File not found')
添加回答
举报