__setitem__(self,key,value):
这个方法应该以与键相关联的方式存储值,以便之后能够使用__setitem__来获取。当然,这个对象可变时才需要实现这个方法。
class Tag: def __init__(self): self.change={'python':'This is python', 'php':'PHP is a good language'} def __getitem__(self, item): print('调用getitem') return self.change[item] def __setitem__(self, key, value): print('调用setitem') self.change[key]=value a=Tag() print(a['php']) a['php']='PHP is not a good language' print(a['php'])
输出:
调用getitem
PHP is a good language
调用setitem
调用getitem
PHP is not a good language