問題在於:如何定義帶有不可變鍵值但可變值的Python字典?我想出了這個(在蟒蛇2.x):定義一個帶有不可變鍵值但可變值的Python字典
class FixedDict(dict):
"""
A dictionary with a fixed set of keys
"""
def __init__(self, dictionary):
dict.__init__(self)
for key in dictionary.keys():
dict.__setitem__(self, key, dictionary[key])
def __setitem__(self, key, item):
if key not in self:
raise KeyError("The key '" +key+"' is not defined")
dict.__setitem__(self, key, item)
但它在我看來(不出意料),而不是馬虎。特別是,這是安全的還是有實際更改/添加一些鍵的風險,因爲我是從字典繼承? 謝謝。
那麼,有人可能會在'FixedDict'的實例上調用'dict .__ setitem __()',不是嗎? – cdhowie 2013-02-11 16:28:48
你應該檢查以確保'dict.update'調用'__setitem__' - 雖然,即使它確實,我不確定這是否與實現有關... – mgilson 2013-02-11 16:28:57
('update'繞過'__setitem__' ) – katrielalex 2013-02-11 16:32:15