Considerations for python 3.2

Source: Internet
Author: User
Tags define abstract

Python version 3, also knownPython 1, 3000OrPy3k(The nickname used to follow the Microsoft Windows 2000 operating system)Programming LanguageThe latest version. Although the new version has made many improvements to the core language, it still breaks the backward compatibility with version 2.x. Other changes have long been expected, such:

    • Real division-for example,1/2The returned result is. 5.
    • LongAndIntThe type is unified into one type, and the suffix is deleted.L.
    • True,FalseAndNoneAll are keywords.

This article-Python 3 SeriesArticleIn the first article-the content covers the newPrint ()Function,Input (), Input/output (I/O) changes, newBytesChanges in data type, string and string formatting, and built-inDictType Change. This article is intended for programmers who are familiar with Python and interested in new version changes, but do not want to bother reading all the python enhancement proposal (PEP.

Now you will need to get your fingers used to typingPrint ("hello ")Instead of the originalPrint "hello"This is becausePrintIt is a function, not a statement. I know, it's a bit painful. Every Python I knowProgramEmployee-once Version 3 is installed and the error "incorrect syntax" is returned, the system will throw at it. I know these two additional symbols are annoying; I also know that this will undermine backward compatibility. However, this change is beneficial.

Let's consider the situation where we need to redirect the standard output (stdout) to a log. In the following example, the log.txt file is opened for append and the object is specifiedFID. Then, usePrint>Redirects a string to a file.FID:

>>> FID = open ("log.txt", "A") >>>> print >> FID, "log text"

Another example is to redirect to a standard error (SYS. stderr ):

>>> Print> SYS. stderr, "An error occurred"

Both examples are good, but there are better solutions. The new syntax only requiresPrint ()Function keyword ParameterFileYou can pass a value. For example:

>>> FID = open ("log.txt", "A") >>> print ("log.txt", file = FID)

SuchCodeThe syntax is clearer. Another advantage is thatSEPYou can change the Separator by passing a string to the keyword parameter.EndIf the keyword parameter is passed to another string, the end string can be changed. To change the delimiter, you can use:

>>> Print ("foo", "bar", SEP = "%") >>> Foo % bar

In general, the new syntax is:

Print ([object,...] [, SEP = ''] [, end = 'endline _ character_here '] [, file = redirect_to_here])

Square brackets ([]. By defaultPrint ()Itself, the result will append a line break (\ N).

 

From raw_input () to input ()

In Python version 2.x,Raw_input ()Reads an input from the standard input (SYS. stdin), returns a string, and removes the linefeed from the end. The following example usesRaw_input ()Obtain a string from the command prompt, and then assign the valueQuest.

>>> Quest = raw_input ("What is your quest? ") What is your quest? To seek the Holy Grail.> quest 'to seek the Holy Grail .'

In Python 2.xInput ()A function requires a valid Python expression, such3 + 5.

At first, someone suggestedInput ()AndRaw_input ()It is deleted from the built-in namespace of Python, so you need to import it to obtain the input capability. This is not correct from the method; because, simply type:

>>> Quest = input ("What is your quest? ")

Will be changed:

>>> Import sys >>> print ("What is your quest? ") >>> Quest = SYS. stdin. Readline ()

It is too cumbersome for a simple input and hard to understand for a newbie. Often need to tell themModuleAndImportWhat is going on, how the string output and the period operator work (so troublesome, there is no difference with the Java language ). Therefore, in Python 3Raw_input ()RenameInput ()In this way, data can be obtained from standard input without importing. If you want to retainInput ()Function, availableEval (input ()), The effect is basically the same.

 

About bytes

New data types bytes literal andBytesThe object is used to store binary data. This object is an unchangeable integer sequence from 0 to 127 or a pure ASCII character. Actually, it is in version 2.5.BytearrayThe version of the object cannot be modified. OneBytes literalIs a prefixB-For example,B 'byte literal'. Calculation of bytes literal generates a newBytesObject. AvailableBytes ()Function to create a newBytesObject.BytesObject constructor:

Bytes ([initializer [, encoding])

For example:

>>> B = (B '\ xc3 \ x9f \ X65 \ x74 \ x61')> Print (B) B '\ xc3 \ x83 \ xc2 \ x9feta'

CreatesBytesObject, but this is redundant, because it can be created by assigning a byte literal value.BytesObject. (I just want to explain that this is feasible, but I do not recommend that you do so .) If you want to use iso-8859-1 encoding, try the following:

>>> B = bytes ('\ xc3 \ x9f \ X65 \ x74 \ x61', 'iso-8859-1 ') >>> print (B) B '\ xc3 \ x83 \ xc2 \ x9feta'

If the initializer is a string, an encoding is required. If the initiator is a bytes literal, you do not need to specify the encoding type. Remember that bytes literal is not a string. But similar to a string, it can be connected to multiple Bytes:

>>> B 'hello 'B' World 'B' Hello world'

UseBytes ()The method represents binary data and encoded text. ToBytesToStr,BytesThe object must be decoded (this will be detailed later ). Binary dataDecode ()Method encoding. For example:

>>> B '\ xc3 \ x9f \ X65 \ x74 \ x61'. Decode () 'ß ETA'

You can also directly read binary data from the file. See the following code:

>>> DATA = open('dat.txt ', 'rb'). Read () >>> print (data) # data is a string >>># content of data.txt printed out here

Its function is to open a file to read a file object in binary mode and read the entire file.

 

String

Python has a single string typeStrThe function is similar to the Unicode type of version 2.x. In other words, all strings are Unicode strings. And-it is very convenient for non-Latin text users-non-ASCII identifiers are now allowed. For example:

>>> César = ["author", "consultant"] >>> print (César) ['author', 'sultant']

In versions earlier than python,Repr ()The method converts an 8-bit string to ASCII. For example:

>>> Repr (''') "'\ xc3 \ xa9 '"

Now, it returns a unicode string:

>>> Repr '"

As I mentioned earlier, this string is a built-in string type.

String objects and byte objects are incompatible. If you want to get a byte string representation, you need to use itsDecode ()Method. If you want to get bytes literal representation from this string, you can useEncode ()Method.

 

Changes in string formatting

Many Python programmers feel the built-in%The operator is too limited because:

    • It is a binary operator and can only accept two parameters at most.
    • Except for formatting string parameters, all other parameters must be squashed using a tuple or dictionary.

This formatting is somewhat inflexible, so Python 3 introduces a new string formatting method (version 3 retains%Operator andString. TemplateModule ). String objects now all have a methodFormat ()This method accepts location parameters and keyword parameters, both of which are passedReplacement Field. The replacement field is enclosed by curly brackets ({}. The element in the replacement field is simply calledField.The following is a simple example:

>>> "I love {0}, {1}, and {2 }". format ("eggs", "bacon", "sausage") 'I love eggs, bacon, and sausage'

Field{0},{1}And{2}Location parametersEggs,BaconAndSausagePassedFormat ()Method. The following example shows how to useFormat ()Format by passing keyword parameters:

>>> "I love {A}, {B}, and {c }". format (A = "eggs", B = "bacon", c = "sausage") 'I love eggs, bacon, and sausage'

Here is another example that combines location parameters and keyword parameters:

>>> "I love {0}, {1}, and {Param }". format ("eggs", "bacon", Param = "sausage") 'I love eggs, bacon, and sausage'

Remember that placing a non-Keyword parameter after a keyword parameter is a syntax error. To escape curly braces, use double curly braces, as shown below:

>>> "{0}". Format ("can't see me") '{0 }'

Location parametersCan't see meIt is not output because no field can be output. Note that this will not produce errors.

NewFormat ()Built-in functions can format a single value. For example:

>>> Print (format (10.0, "7.3g") 10

In other words,GWhich indicatesGeneral FormatWhich outputs a fixed width value. The first value before the decimal point specifies the minimum width, and the value after the decimal point specifies the precision. The complete Syntax of format specifier is beyond the scope of this article. For more information, see.

Built-in dict type changes

Another major change within 3.0 is within the dictionary.Dict. iterkeys (),Dict. itervalues ()AndDict. iteritems ()Method. Instead. Keys (),. Values ()And. Items ()They are patched to return lightweight container objects similar to a set, rather than a list of keys and values. The advantage is that you can executeSetOperation. For example:

>>> D = {1: "dead", 2: "parrot" }>>> print (D. items () <built-in method items of dict object at 0xb7c2468c>

Note:In python,SetIs an unordered set of unique elements.

Here, I created a dictionary with two keys and values, and then outputD. Items ()The returned value is an object, not a list of values. Can be likeSetThe object tests the membership of an element, for example:

>>> 1 in D # Test for membershiptrue

InDict_valuesAn example of an object entry iteration:

>>> For values in D. Items ():... print (values)... deadparrot

However, if you do want to obtain a list of values, you canDictObject. For example:

>>> Keys = List (D. Keys () >>> print (KEYS) [1, 2]

Back to Top

New I/O

Metadata

Wikipedia defines meta classes as follows:MetadataIs such a class, and its instance is also a class ." In part 1 of this series, I will introduce this concept in detail.

Before studying the new I/O mechanism, it is necessary to take a look at abstract base classes (ABC ). A more in-depth introduction will be provided in part 1 of this series.

ABCIs a class that cannot be instantiated. To use ABC, The subclass must inherit this ABC and overwrite its abstract method. If the method prefix is used@ AbstractmethodDecorator, this method is an abstract method. The new ABC framework also provides@ AbstractpropertyModifier to define abstract attributes. You can import the standard library moduleABCTo access this new framework. Listing 1 shows a simple example.

Listing 1. A simple abstract base class

From ABC import abcmetaclass simplegateactclass (metaclass = abcmeta): passsimplegateactclass. Register (list) assert isinstance ([], simplegateactclass)

Register ()A method call accepts a class as its parameter and makes ABC a subclass of the registered class. You can callAssertStatement. Listing 2 is another example using modifiers.

Listing 2. An abstract base class using modifiers

From ABC import abcmeta, abstractmethodclass abstract (metaclass = abcmeta): @ abstractmethod def absmeth (Self): pass class A (abstract): # must implement abstract method def absmeth (Self ): return 0

After learning about ABC, we can continue to explore new I/O systems. Previous Python releases lack some important but outstanding functions, suchSeek ().Object similar to streamYesRead ()AndWrite ()Methods are similar to object objects, such as socket or files. Python 3 has many I/O layers for stream-like objects-a raw I/O layer, a buffered I/O layer, and a text I/O layer-each each layer is defined by its own ABC and implementation.

To open a stream, you still need to use the built-inOpen (filename)Function, but it can also be calledIo. Open (filename )). In this case, a buffered text file is returned;Read ()AndReadline ()Returns a string (note that all strings in Python 3 are Unicode ). You can also useOpen (filename, 'B ')Open a buffered binary file. In this case,Read ()Returns bytes,Readline ()It cannot be used.

This built-inOpen ()The constructor of the function is:

Open (file, mode = "r", buffering = none, encoding = none, errors = none, newline = none, closefd = true)

Possible modes include:

    • R:Read
    • W:Open for writing
    • A:Open for append
    • B:Binary Mode
    • T:Text mode
    • +:Open a disk file for update
    • U:General line feed mode

The default mode isRTTo open the text mode for reading.

BufferingThe expected value of the keyword parameter is one of the following three Integers to determine the buffer policy:

    • 0:Disable buffering
    • 1:Row Buffer
    • > 1:Full buffer (default)

The default encoding method is independent from the platform. Disable the file descriptor orClosefdIt can be true or false. If it is false, the file descriptor will be retained after the file is closed. If the file name does not workClosefdIt must be set to true.

Open ()The returned object depends on the mode you set. Table 1 provides the return type.Table 1. Return types for different open Modes

Mode Returned object
Text mode Textiowrapper
Binary Bufferedreader
Write binary Bufferedwriter
Append binary Bufferedwriter
Read/write mode Bufferedrandom

Note:The text mode can beW,R,WT,RT.

The example shown in listing 3 opens a buffered binary stream for reading.

Listing 3. Open a buffered binary stream for reading

>>> Import Io >>> F = Io. open ("hashlib. pyo "," rb ") # Open for reading in binary mode >>> F # F is a bufferedreader object <Io. bufferedreader object at 0xb7c2534c >>>> F. close () # Close stream

BufferedreaderObjects can access many useful methods, suchIsatty,Peek,Raw,Readinto,Readline,Readlines,Seek,Seekable,Tell,Writable,WriteAndWritelines. To view the complete list, you canBufferedreaderObject runningDir ().

 

Conclusion

PythonCommunityWill it be answered ?? Version 3 is still under speculation. Breaking backward compatibility means that the two versions will be supported. Some project developers may not want to migrate their projects, even if version 2 to 3 is used. Personally, I found that migrating from Python version 2 to Python 3 is just a new understanding of several things: It certainly does not change as strongly as migrating from Python to Java or Perl. Many changes have long been unexpected, suchDict. RunPrint ()Far more than executing JavaSystem. Out. println ()It is much easier and easier to learn, so it can indeed bring some benefits.

I guess some posts in blogosphere will make Python supporters mistakenly think of some of these changes-for example, breaking backward compatibility-with destructive effects. Lambda was prepared to be deleted, but it never did. It still retains its original format. For a complete list of retained projects, visit the python core development site. If you are willing to go deep into the pep, you will be able to get more in-depth information.

The next article in this series will cover more advanced topics, such as metadata syntax, ABC, modifier, integer literal support, base type, and exception.

 

Related Article

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.