__getattribute__和item系列
# class Foo: # def __init__(self,x): # self.x=x # # def __getattr__(self, item): # print('执行的是我') # # return self.__dict__[item] # # f1=Foo(10) # # print(f1.x) # f1.xxxxxx #不存在的属性访问,触发__getattr__ class Foo: def __init__(self,x): self.x=x def __getattr__(self, item): print('执行的是getattr') # return self.__dict__[item] # def __getattribute__(self, item): # print('执行的是getattribute') # raise AttributeError('抛出异常了') # raise TabError('xxxxxx') f1=Foo(10) # f1.x f1.xxxxxx #不存在的属性访问,触发__getattr__
item系列
class Foo: def __getitem__(self, item): print('getitem',item) 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() print(f1.__dict__) # f1.name='egon' #---->setattr-------->f1.__dict__['name']='egon' f1['name']='egon'#--->setitem--------->f1.__dict__['name']='egon' f1['age']=18 print('===>',f1.__dict__) # del f1.name # print(f1.__dict__) # # print(f1.age) del f1['name'] print(f1.__dict__) print(f1['age']) raise S