考虑代理
dict而不是子类化。这意味着只允许使用您定义的方法,而不能使用
dict的实现。
class FixedDict(object): def __init__(self, dictionary): self._dictionary = dictionary def __setitem__(self, key, item): if key not in self._dictionary: raise KeyError("The key {} is not defined.".format(key)) self._dictionary[key] = item def __getitem__(self, key): return self._dictionary[key]另外,您应该使用字符串格式而不是
+生成错误消息,因为否则,如果不是字符串,则它将崩溃。



