#__getitem__ __setitem__ __delitem__运行设置key value值了
class fun:
def __init__(self):
print('test')
def run(self):
print('run')
def __getitem__(self, item):
print('__getitem__','item:',item)
def __setitem__(self, key, value):
print('__setitem__','key:',key,'value:',value)
self.__dict__[key] = value #设置字典值,print(f.__dict__)否则打印为空
def __delitem__(self, key):
print('__delitem__','key',key)
self.__dict__.pop(key) #删除字典值
f = fun()
f.run()
f['sn'] = 1231
f['name'] = 1 #设置值的时候,执行__setitem__
f['name'] #获取值的时候,执行__getitem__
del f['name'] #删除值的时候,执行__delitem__
print(f.__dict__) #结果是{'sn': 1231}