__setattr__,__getattr__,__delattr__

class Foo: 
    the X- = 1
     DEF  __init__ (Self, the y-): 
        self.y = the y-
     DEF  __getattr__ (Self, Item):
         Print ( " ----> from getattr: you find a property does not exist " )
     DEF  __setattr__ (Self , Key, value):
         Print ( ' ----> from setattr ' )
         # self.key value = # this infinite recursion 
        # Self .__ dict __ [Key] = value # should be written 
    DEF  __delattr__ (Self, Item):
         Print ( " ---> from delattr" )
         # Del self.item 
        # above wording will also infinite recursion 
        Self. __Dict__ .pop (Item)
     DEF  __getitem__ (Self, Item):
         Print ( ' ----> from getItem ' )
     DEF  __setitem__ (Self, Item, value):
         Print ( ' --- from setitem ' )
     DEF  __delitem__ is (Self, Item):
         Print ( ' ----> from __delitem__ is ' )
 # __setattr__: add / modify attributes will trigger its execution 
# principle to write that is, the attributes and values written into the object underlying the dictionary, and we re-write
# __Setattr__ method, it is not written into the underlying dictionary. 
Foo = F1 (10 ) 
F1 [ ' Y ' ] = 10   # trigger __setitem__ method 
Print (F1. the __dict__ )
 Print (F1. the __dict__ ) 
f1.z =. 3 # # trigger __setattr__ 
Print (F1. the __dict__ )
 # unless the underlying dictionary directly, otherwise we can never be assigned 
f1. __dict__ [ ' z ' ] = 3
 Print (f1.z) # 3 
# at this time there will be a z property f1 
# __delattr__ delete attributes will trigger when 
f1 .the __dict__ [ ' A ' ] =. 5
 Print (F1. the __dict__ ) # { 'Z':. 3, 'A':. 5} 
del f1.a # trigger __delattr__ method 
del F1 [ ' A ' ] # trigger __delitem__ methods 
Print (f1. __dict__ ) # { 'z': 3} 
# __getattr__ only at the point of calling the properties and the property does not exist when will trigger 
f1.anc # Print: ----> from getattr: you do not find the properties there is 
f1 [ ' ANC ' ] # Print: ----> from getitem: you're looking for does not exist property

 

Guess you like

Origin www.cnblogs.com/cong12586/p/11371935.html