Python Basics---->python Use (vii)

Source: Internet
Author: User
Tags serialization wrapper

Here is a note of Python's knowledge of Io, adorners, and serialization. the face of the river I am infinitely ashamed, I wasted time, empty a tired, and all the dream for the horse as a poet, the years are easy to die a drop not left.

Some knowledge of Python one, the use of adorners in Python

Print a word before calling the now function, @log placed above the definition of the function.

deflog (func):defWrapper (*args, * *Kwargs):Print('Call %s ():'% func.__name__)        returnFunc (*args, * *Kwargs)returnWrapper@logdefNow ():Print('2017-12-12') Now ()Print(now.)__name__)

The results of the operation are as follows:

Call Now (): -wrapper 

If you need to pass parameters in the adorner, you need to nest more layers outside.

deflog (text):defDecorator (func):defWarpper (*args, * *Kwargs):Print('%s%s ():'% (text, func.)__name__))            returnFunc (*args, * *Kwargs)returnWarpperreturnDecorator@log ('Hello World')defNow ():Print('2017-12-12') Now ()Print(now.)__name__)

The results of the operation are as follows:

Hello World Now (): -warpper 

The above two kinds of now.__name__ changed to Warpper, a complete example is as follows:

Import Functools def log (func):    @functools. Wraps (func)    def Wrapper (*args, * *kw)        :Print ('call%s ():' % func.  __name__)        return func (*args, * *kw    )return Wrapper

Import Functools is importing the Functools module. The concept of the module is explained later. Now, just remember to add @functools.wraps (func) in front of the definition wrapper ().

Second, the use of partial function in Python
#use of partial functionsPrint(Int ('12345', base=8))Print(Int ('12345', base=16))#In This we define a binary function.defInt2 (x, base=2):    returnInt (x, base)Print(Int2 ('100101010'))#298#with the partial function, the parameters of a function can be fixed directlyImportFunctoolsint2= functools.partial (int, base=2)Print(Int2 ('101001010'))# the

Iii. use of Stringio and Bytesio
 fromIoImportstringiof=Stringio () f.write ('Hello') F.write (' World')Print(F.getvalue ())#Hello World#read the Stringio dataf = Stringio ('Hello!\nhi!\ngoodbye') whiletrue:s=F.readline ()ifs = ="':         Break    Print(S.strip ())#Stringio can only operate STR, if it is binary data, it is necessary to use Bytesio fromIoImportbytesiof=Bytesio () f.write ('English'. Encode ('Utf-8'))Print(F.getvalue ())

The results of the operation are as follows:

Hello Worldhello! Hi! Goodbyeb ' \xe4\xb8\xad\xe6\x96\x87 '

Iv. module OS operating directory and files in Python
#name of the systemImportOSPrint(Os.name)#Environment VariablesPrint(Os.environ)Print(Os.environ.get ('Java_home'))#operation of files and directoriesPrint(Os.path.abspath ('.'))#G:\Java\Go\program\2017-05-18\LearnPython1\test10\ioPrint(Os.path.join ('C:/users/michael','TestDir')) Os.mkdir (Os.path.join ('C:/users/michael','/testdir'))#get the directory and file name of the filedirectory, filename = Os.path.split ('/users/michael/testdir/file.txt')Print(directory)Print(filename)#get the suffix of the filePrint(Os.path.splitext ('/path/to/file.txt') [1])#. txt#modify file names and delete filesOs.rename ('Test.txt','test.py') Os.remove ('test.py')#Copying of filesImportShutilshutil.copyfile ('/user/huhx.txt','/user/linux.txt')

V. Serialization in Python
ImportPickled= Dict (name='Huhx', Age=20, score=80)Print(Pickle.dumps (d))#B ' \x80\x03}q\x00 (x\x04\x00\x00\x00nameq\x01x\x04\x00\x00\x00huhxq\x02x\x03\x00\x00\x00ageq\x03k\x14x\x05\ X00\x00\x00scoreq\x04kpu. '#Serialization off = open ('Dump.txt','WB') Pickle.dump (d, f) f.close ()#deserializationf = open ('Dump.txt','RB') d=pickle.load (f) f.close ()Print(d)#{' name ': ' Huhx ', ' age ': ' Score ':ImportJSONPrint(Json.dumps (d))#{"name": "Huhx", "age": +, "score":Json_str='{"Age": +, "score": "," "Name": "Bob"}'Print(Json.loads (JSON_STR))#{' age ': ' Score ': ' The ' name ': ' Bob '}

Friendship Link

Python Basics---->python Use (vii)

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.