A __setattr__,__delattr__,__getattr__
- __setattr__ #添加/Modify a property will trigger its execution
- __delattr__ #删除属性的时候会触发
- __getattr__ #只有在调用属性且属性不存在的时候才会触发
classFoo:def __init__(self,x): Self.name=xdef __setattr__(self, Key, value):#if not isinstance (VALUE,STR): #raise TypeError (' must be str ') #print ('----setattr---key:%s,value:%s '% (key,value)) #print (Type (key)) #print (type (value)) #Self.key=value #setattr (Self,key_str,value) #self. Key_attribute=value #这是无限递归Self.__dict__[Key]=value#because you rewrite the __setattr__, any assignment operation will trigger its operation, you do not write anything, is not assigned at all, unless you directly manipulate the property dictionary, otherwise you can never assign a value def __delattr__(self, item):Print('delattr:%s'%Item)Print(Type (item))#delattr (self,item) #这是无限递归 #del Self.itemSelf.__dict__. Pop (item)#we can directly modify the property dictionary to complete the operation of adding/modifying propertiesF1=foo ('Egon')#f1.name= ' Egon 'F1.age=18Print(F1.__dict__)Print(F1.name)Print(f1.age)Print(F1.__dict__)delF1.agePrint(F1.__dict__)Print(f1.age)#---------------------getattr------------------------classFoo:def __init__(self,x): Self.name=x#Is triggered if the property does not exist def __getattr__(self, item):Print('getattr-->%s%s'%(Item,type (item))) F=foo ('Egon')#print (f.name)Print(F.XXXXXXX)Kick Stunt
Python basics such as __setattr__,__delattr__,__getattr__