New Features of Python 3 zz

Source: Internet
Author: User

Python version 3, also knownPython 1, 3000OrPy3K(Like Microsoft Windows 2000) is the latest version of the general programming language Guido van rosum. 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-the first in the Python 3 Series-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. (The references later in this article provide links to these PEP .)

New print () function

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 programmer I know-once Version 3 is installed and the error "incorrect syntax" is returned, it 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)

Such code makes the syntax 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).

Back to Top

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.

Back to Top

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.

Back to Top

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', 'consultant']

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.

Back to Top

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 the references section of this article.

Back to Top

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 membership
True

Indict_valuesAn example of an object entry iteration:

>>>for values in d.items():
... print(values)
...
dead
parrot

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 ABCMeta

class SimpleAbstractClass(metaclass=ABCMeta):
pass

SimpleAbstractClass.register(list)

assert isinstance([], SimpleAbstractClass)

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, abstractmethod

class 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().

Back to Top

Conclusion

Will the Python community be connected ?? 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.

References

Learning

  • For more information, see the original article on the developerWorks global website.

  • For the complete Syntax of format specifier, visit the Python core development site.
  • Read related Python 3 PEP:
    • Pep 3111: simple input built-in Python 3000
    • Pep 3116: New I/O
    • Pep 3138: String Representation in Python 3000
    • PEP 3112: Bytes literals in Python 3000
    • PEP 3137: Immutable Bytes and Mutable Buffer
    • PEP 3106: Revamping dict. keys (),. values () &. items ()
    • PEP 3108: Standard Library Reorganization
    • PEP 3100: Miscellaneous Python 3.0 Plans

  • See the Meta class on Wikipedia.
  • View computer courses, including abstract classes on Wikipedia.
  • Read Guido van rosum's paper.
  • Understand the unordered set orSet.
  • In the developerworks Linux area, find more references for Linux developers (including new Linux beginners) and refer to our most popular articles and tutorials.
  • Read all Linux tips and Linux tutorials on developerworks.
  • Stay tuned to developerworks technical events and network broadcasts.

Obtain products and technologies

  • Obtain the latest version of Python.

  • Build your next Linux development project with IBM trial software that can be downloaded directly from developerworks.

Discussion

Join the developerWorks community through blogs, forums, podcast, and spaces.

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.