1 class Foo: 2 def __init__(self,name): 3 self.name=name 4 def __call__(self, *args, **kwargs): 5 print('====>') 6 f=Foo('egon') 7 f() 8 9 class Foo: 10 def __init__(self,name): 11 self.name=name 12 def __getitem__(self,item): 13 print('getitem',self.__dict__) 14 return self.__dict__[item] 15 def __setitem__(self, key, value): 16 print('setimtem') 17 self.__dict__[key]=value 18 def __delitem__(self, key): 19 print('del obj[key]时,我执行') 20 self.__dict__.pop(key) 21 f=Foo('egon') 22 # print(f['name']) #f.name 23 f['x']=1 24 # print(f.__dict__) 25 del f['x'] 26 print(f.__dict__) 27 28 f1=Foo('sb') 29 f1['age']=18 30 f1['age1']=19 31 del f1.age1 32 del f1['age'] 33 f1['name']='alex' 34 print(f1.__dict__)
====> setimtem del obj[key]时,我执行 {'name': 'egon'} setimtem setimtem del obj[key]时,我执行 setimtem {'name': 'alex'}