Python3 Magic Method: Descriptor (The implementation principle of the property)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.