1 class Foo: 2 def __getitem__(self, item): 3 print('getitem') 4 return self.__dict__[item] 5 6 def __setitem__(self, key, value): 7 self.__dict__[key] = value 8 9 def __delitem__(self, key): 10 print('delitem') 11 del self.__dict__[key] 12 13 pass 14 15 16 f1 = Foo() 17 f1[1] = 3 18 print(f1.__dict__) 19 f1['age'] = 27 20 f1['name'] = '小白' 21 del f1['name'] 22 print(f1.__dict__) 23 输出: 24 {1: 3} 25 delitem 26 {1: 3, 'age': 27}
该方法同__getattr__内置方法一样