类的专有方法(__getitem__和__setitem__)

时间:2021-01-03 16:47:13
# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#http://www.imooc.com/code/6252 #类的专有方法(__getitem__和__setitem__)
#__getitem__,返回给定键对应的值
#__setitem__,设置给定键对应的元素 class Test():
kk={}
def __getitem__(self,key):
return self.kk[key]
def __setitem__(self,key,value):
self.kk[key]=value test=Test()
test['fengmei']=25
print test['fengmei']# print test.__getitem__('fengmei')#
test.__setitem__('xiaodeng',28)
print test.__getitem__('xiaodeng')#