This attr series is the Egon teacher self-created, individual or can accept this cultural heritage, so directly to use, but also without vainly disobey sense of
The so-called attr series, in fact, is the __setattr__,__delattr__,__getattr__ three functions, from the name can be seen that this is a set of settings, delete, query function, then we come to one of the look:
__setattr__ (self): a function that fires when an attribute in a class is "assigned"
code example:
1 classTeacher:2 def __init__(self):3Self.name ="Egon"4 def __setattr__(Self, key, value):#when Self.name is assigned, the function __setattr__5Self.__dict__[Key] = value
#Storing Name:egon in the self namespace is the addition of a key-value pair in the dictionary (key:value)6 Print(Key,"has been assigned a value:", value)7 8Te = Teacher ()#instantiate the teacher class, at which point the assignment of Self.name has been set9 Ten #name has been assigned: Egon
__delattr__ (self): a function that fires when a property in a class is "deleted"
code example:
classTeacher:def __init__(self): Self.name="Egon" def __delattr__(Self, item):#when Self.name is assigned, the function __delattr__Self.__dict__. Pop (item)#Remove the name key along with value in the Self namespace Print(Item,"has been deleted") Te=Teacher ()delTe.name#trigger the method execution of __delattr__ ()
__getattr__ (self): The function that is triggered when the name of the call, "there is no occurrence in instantiating an object or class"
code example: Be sure to note that this is triggered when no name is found
1 classTeacher:2 def __init__(self):3Self.name ="Egon"4 def __getattr__(Self, item):#performs a secondary function when no property or method is found5 Print("No", Item,"Properties")6 7Te =Teacher ()8Te.sbegon#It is obvious that teacher and Te are not sbegon this property or method, so triggering the __getatter__ () method
The above is a small summary of the ATTR series
Python Concept-attr series (Lamb taught)