class Foo: def __init__(self, type): self.type = type def __getattr__(self, item): print('__getattr__') def __getitem__(self, item): print('__getitem__') # return self.__dict__[item] def __setitem__(self, key, value): print('__setitem__') self.__dict__[key] = value def __delitem__(self, key): print('__delitem__') self.__dict__.pop(key) f1 = Foo('people') print(f1.__dict__) # {} f1['name'] = 'alex' # __setattr__不支持此种方式,会报错;此时触发的是__setitem__ f1.age = 18 # 此时没有触发__setitem__,但也添加成功了,说明触发的是__setattr__ print(f1.__dict__) # {'name': 'alex', 'age': 18} del f1['name'] # 此时触发的是__delitem__ # del f1.age # 此时没有触发__delitem__,但也删除成功了,说明触发的是__delattr__ print(f1.__dict__) # f1['addr'] # 没有此属性,打印__getitem__,说明触发了__getitem__ # f1.addr # 打印__getattr__,同上 # print(f1.type) # print(f1['type']) # 有此属性,打印__getitem__,说明触发了__getitem__