1. Descriptors
A class is used to describe the properties of another class, and the class that describes the property must implement __get__ __set__ __delete__ one of the magic methods, then the class that describes the property is called the descriptor
In short, a descriptor is a property that assigns a class of a particular type (containing __get__ __set__ __delete__) to another class
2. Magic method
__get__ (Self,instance,owner)# Owner is a class that contains a descriptor, instance is an object that contains a descriptor class instantiation
Used to access the property, return the value of the property
__set__ (Self,instance,value)
Called in the property assignment operation, does not return any values
__DELETE__ (self,instance)
Defines the behavior of the descriptor value being deleted and does not return a value
Example : Defining a temperature class, using descriptors, to achieve any conversion of degrees Celsius and degrees Fahrenheit
classCelsius:def __init__(self,value=26.0): Self.value=valuedef __get__(Self,instance,owner):#print (Self,instance,owner) returnSelf.valuedef __set__(self,instance,value): Self.value=valueclassFahrenheit:def __get__(Self,instance,owner):#print (instance) returnInstance.cel*1.8+32#instance temperature instantiated objects A,owner to temperature this class def __set__(self,instance,value): Instance.cel= (value-32)/1.8classTemperature:cel=Celsius () Fah=Fahrenheit () a=temperature ()
Defines a descriptor record descriptor that records the specified variable read and write operations and saves them as files Record.txt
Import TimeImportOSclassRecord:def __init__(self,value,name): Os.chdir (OS.GETCWD ()) Self._value=value Self._name=namedef __get__(self,instance,owner): File=open ('Record.txt','a') TIM=time.strftime ("%c") File.write ('%s variable was read at Beijing time%s =%d\n'%(Self._name,tim,self._name,self._value)) File.close ()returnSelf._valuedef __set__(self,instance,value): Self._value=Value File=open ('Record.txt','a') TIM=time.strftime ("%c") File.write ('%s variable was modified in Beijing time%s =%s\n'%(Self._name,tim,self._name,self._value)) File.close ()classtest:x= Record (10,'x') y= Record (8.8,'y') Test=test ()
Define a descriptor Mydes descriptor, use the Pkl file to store the corresponding property, and delete the file when the property is deleted
ImportPickle as PImportOSclassMydes:save=[] def __init__(self, Name): Os.chdir (os.curdir) self._name=namedef __get__(Self,instance,owner):ifSelf._name not inchSelf.save:RaiseAttributeerror ("The %s property is not assigned a value"%self._name)Else: returnSelf.valuedef __set__(Self,instance,value): Self.save.append (self._name) Self.value=Value File=open ((self._name+'. PKL'),'WB') P.dump (value,file) file.close ()def __delete__(self,instance): Os.remove ((Self._name+'. PKL')) Self.save.remove (self._name)classtest:x= Mydes ('x') y= Mydes ('y') Test=test ()
Python3 Magic Method: Descriptor (The implementation principle of the property)