我有以下类,用于存储要访问的其他对象的设置:
#!/usr/bin/env python
class Settings:
"""Singleton settings class"""
settings = {
'SectionA': {'a': 1, 'b': 2, 'c': 3},
'SectionB': {'d': 4, 'e': 5, 'f': 6}
}
def __getitem__(self, key): return self.settings[key]
def __setitem__(self, key, item): self.settings[key] = item
def keys(self): return self.settings.keys()
s = Settings()
print s.keys()
print s['SectionA']
print s['SectionB']
for key in s: print s[key]
我不明白为什么它会产生以下输出或如何解决它,非常感谢任何帮助:
foo@bar:~$ python Settings.py
['SectionB', 'SectionA']
{'a': 1, 'c': 3, 'b': 2}
{'e': 5, 'd': 4, 'f': 6}
Traceback (most recent call last):
File "Settings.py", line 20, in <module>
for key in s: print s
File "Settings.py", line 11, in __getitem__
def __getitem__(self, key): return self.settings[key]
KeyError: 0
foo@bar:~$