# 对象作为len()函数的参数是必须实现该方法
__len__
# 使用类似字典方式访问成员时必须实现 dic['pro_name']
__getitem__
# 使用类似字典方式设置成员时必须实现 dic['pro_name']='asdf'
__setitem__
# 使用类似字典方式删除成员时必须实现 delete dic['pro_name']
__delitem__
class DictDemo:
def __init__(self,key,value):
self.dict = {}
self.dict[key] = value
def __getitem__(self,key):
return self.dict[key]
def __setitem__(self,key,value):
self.dict[key] = value
def __len__(self):
return len(self.dict)
dictDemo = DictDemo('key0','value0')
print(dictDemo['key0']) #value0
dictDemo['key1'] = 'value1'
print(dictDemo['key1']) #value1
print(len(dictDemo)) #2
http://blog.csdn.net/yuan_j_y/article/details/9317817