2 回答

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
我認(rèn)為此實(shí)現(xiàn)適合您的需求:
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__,沒有無限遞歸,通過點(diǎn)表示法訪問。

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
愚蠢,但我找到了更優(yōu)雅的方法來解決我的問題。
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')
添加回答
舉報(bào)