dict的赋值和取值,形如
赋值test[‘key’]=value
取值test[‘key’]
这两个表达方式的本质是类中的两个实例方法__setitem__和__getitem__
直接上代码
class testsetandget:
kk = {}
def __setitem__(self,key,value):
self.kk[key] = value
def __getitem__(self,key):
return self.kk[key]
print dir(testsetandget)
print testsetandget.kk
a = testsetandget()
print a.kk
a['From']='123'
print a['From']
a.__setitem__('To','456')
print a.__getitem__('To')
python中应该有很多类有这样的实现,最近涉及到一个是msg = MIMEText(),可以为邮件加入msg[‘From’],msg[‘To’]等