def__setitem__(self, key, value): if key in self.keys(): raise TypeError('Fuck! Immutable dict!') else: self.data[key] = value
def__delitem__(self, key): if key in self.keys(): raise TypeError('Fuck! Immutable dict!') else: raise KeyError
UserDict类的源码:
classUserDict(MutableMapping): # Start by filling-out the abstract methods def__init__(*args, **kwargs): ifnot args: raise TypeError("descriptor '__init__' of 'UserDict' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) if args: dict = args[0] elif'dict'in kwargs: dict = kwargs.pop('dict') import warnings warnings.warn("Passing 'dict' as keyword argument is deprecated", DeprecationWarning, stacklevel=2) else: dict = None self.data = {} if dict isnotNone: self.update(dict) if len(kwargs): self.update(kwargs) def__len__(self):return len(self.data) def__getitem__(self, key): if key in self.data: return self.data[key] if hasattr(self.__class__, "__missing__"): return self.__class__.__missing__(self, key) raise KeyError(key) def__setitem__(self, key, item): self.data[key] = item def__delitem__(self, key):del self.data[key] def__iter__(self): return iter(self.data)
# Modify __contains__ to work correctly when __missing__ is present def__contains__(self, key): return key in self.data
# Now, add the methods in dicts but not in MutableMapping def__repr__(self):return repr(self.data) defcopy(self): if self.__class__ is UserDict: return UserDict(self.data.copy()) import copy data = self.data try: self.data = {} c = copy.copy(self) finally: self.data = data c.update(self) return c @classmethod deffromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d