class Foo: def __init__(self, name): self.name = name def __getitem__(self, item): print('obj[key]时,我执行') print(self.__dict__[item]) def __setitem__(self, key, value): print('obj[key]=value时,我执行') self.__dict__[key] = value def __delitem__(self, key): print('del obj[key]时,我执行') self.__dict__.pop(key) def __delattr__(self, item): print('del obj.key时,我执行') self.__dict__.pop(item)f1 = Foo('jack')f1['name'] # obj[key]时,我执行 # jackf1['age'] = 18 # obj[key]=value时,我执行f1['age2'] = 19 # # obj[key]=value时,我执行del f1.age # del obj.key时,我执行del f1['age2'] # del obj[key]时,我执行f1['name'] = 'alex' # f1[key]=value时,我执行print(f1.__dict__) # {'name': 'alex'}