Descriptor
A descriptor is a property that assigns an instance of a particular type of class real to another class.
A special type is one or more of the following three methods that are implemented
__get__ (self, instance, Owener)
The value that is used to access the property, its return property
__set__ (self, instance, value)
will be called in the property assignment operation, no content is returned
__delete__ (self, instance)
Control the delete operation without returning any content
property is a descriptor class
>>>classmydecriptor: ...def __get__(Self,instance,owner): ...Print('getting ...', self, instance, owner) ...def __set__(self, instance, value): ...Print('Setting ...', self, instance, value) ...def __delete__(self, instance): ...Print('deleting ...', self,instance) ...>>>classTest: ... x=mydecriptor () ...>>> test =Test ()>>>test.xgetting ...<__main__. Mydecriptor Object at 0x7f43e3b3efd0> <__main__. Test Object at 0x7f43e3b52048> <class '__main__. Test'>>>>Test<__main__. Test object at 0x7f43e3b52048>>>> test.x ='X-man'Setting ...<__main__. Mydecriptor Object at 0x7f43e3b3efd0> <__main__. Test object at 0x7f43e3b52048> XMans>>>deltest.xdeleting ...<__main__. Mydecriptor Object at 0x7f43e3b3efd0> <__main__. Test Object at 0x7f43e3b52048>
The implementation principle of property
>>>classMyProperty: ...def __init__(Self,fget = none, Fset = none, Fdel =None): ... self.fget=fget ... self.fset=fset ... self.fdel=Fdel ...def __get__(Self,instance,owener): ...returnSelf.fget (instance) ...def __set__(self,instance,value): ... self.fset (instance,value) ...def __del__(self,instance): ... Self.fdel (instance) ...>>>classC: ...def __init__(self): ... self.x=None ...defGetX (self): ...returnself.x ...defSetX (self,value): self.x=Value ...>>> C =C ()>>> c.x ='C-man'>>>c.x'C-man'>>>delc.x
Practice Requirements
Define a temperature class first, and then define two descriptor classes to describe the two attributes of Celsius and Fahrenheit.
Two properties are required to be automatically converted, that is, you can assign a value to the attribute in Celsius, and then print the Fahrenheit attribute as the result of the automatic conversion.
>>>classCelsius: ...def __init__(Self,value = 26.0): ... self.value=Float (value) ...def __get__(Self,instance,owner): ...returnself.value ...def __set__(self,instance,value): ... self.value=Value ...>>>classFahrenheit: ...def __get__(Self,instance,owner): ...returnInstance.cel *1.8 +32... def __set__(self,instance,value): ... instance.cel= (float (value)-32)/1.8... >>>classtemperarure: ... cel=Celsius () ... fah=Fahrenheit () ...>>> temp =temperarure ()>>>Temp.cel26.0>>> Temp.cel = 30>>>Temp.fah86.0>>> Temp.fah =100>>>Temp.cel37.77777777777778
PYTHON--28 Descriptor (principle of Preperty)