__getitem__()、__setitem__()与__delitem__()
1 # 如果想要运用[]取值,可以实现__getitem__() 2 # 想要运用[]设值,可以实现__setitem__() 3 # 若想通过del与[]来删除,可以实现__delitem__() 4 class ChainMap: 5 def __init__(self,*maps): 6 self.maps=maps 7 def lookup(self,key): # 查找是否有对应键的字典 8 for m in self.maps: 9 if key in m: 10 return m 11 return None 12 def __getitem__(self, item): # 实现__getitem__()方法 13 m=self.lookup(item) 14 if m: 15 return m[item] 16 else: 17 raise KeyError 18 def __setitem__(self, key, value): # 实现__setitem__()方法 19 m=self.lookup(key) 20 if m: 21 m[key]=value 22 else: 23 self.maps[key]=value 24 def __delitem__(self, key): # 实现__delitem__()方法 25 m=self.lookup(key) 26 if m: 27 del m[key] 28 else: 29 raise KeyError 30 c=ChainMap({'A':'Justin'},{'A':'Monica','B':'Irene'}) 31 print(c.maps) 32 print(c['A']) 33 c['A']='caterpillar' 34 print(c.maps) 35 del c['A'] 36 print(c.maps)