Analysis of the difference between Python3.0 and 2.X version _python

Source: Internet
Author: User
Tags abstract documentation

By enumerating some common examples to analyze the difference between the Python3.0 and the 2.X version, this paper summarizes the author's experience and has a good reference value for the Python program designers. Specifically as follows:

As a front-end development of the Code farmers, recently by reading the latest version of "A byte of Python" and with the old version of "a byte of Python" to compare, found that the Python3.0 in some places or some changes. Then check the official website documentation to summarize the difference:

1. If you download the latest version of Python, you will find that all the Hello World examples in the book will no longer be correct.
The python2.x code is as follows:

Print "Hello world!" #打印字符串 

The Python3.0 code is as follows:

Print ("Hello world!") 

To print the string in parentheses, this kind of writing is very kind to me, the person who studies Java origin, ~o (∩_∩) o~

2.
The python2.x code is as follows:

guess = Int (raw_input (' Enter an integer: ') #读取键盘输入的方法 

The Python3.0 code is as follows:

guess = Int (input (' Enter an Integer: ')) 

The method name becomes more easy to remember!

3.
Added a new nonlocal statement, a non-local variable that ranges between global and local, and is used primarily for function nesting, as follows:

#!/usr/bin/python 
# Filename:func_nonlocal.py 
def func_outer (): 
  x = 2 
  print (' x is ', x) 
  def func_ Inner (): 
    nonlocal x 
    x = 5 
  func_inner () 
  print (' Changed local x to ', x) 
Func_outer () 

4.
VarArgs parameters, do not know what this translation is more appropriate? Let's look at the following example:

#!/usr/bin/python 
# Filename:total.py 
def total (initial=5, *numbers, **keywords): 
  count = initial For number in 
  numbers: 
    count = number for 
  key in keywords: 
    count + = Keywords[key] Return 
  count 
Print (Total (1, 2, 3, vegetables=50, fruits=100)) 

All positional parameters (1,2,3) are passed as a list when the * logo is used in front of the parameter.
All key parameters (Vegetables=50, fruits=100) are passed as a dictionary when the * * identity is used in front of the parameter.

5.
On the topic of packages, personal understanding is limited. Interested readers can consult the relevant documentation.

6.
In the data structure, one more type: Set
Set is a set of unordered simple objects that can be used when we care whether an object exists in a set, and the order and number of occurrences are secondary.

7.
About the Os.sep method (set is separator, the abbreviation for delimiters)
Take a look at the author's example of a very faint dish:
The python2.x code is as follows:

Target_dir = '/mnt/e/backup/' 
target = target_dir + time.strftime ('%y%m%d%h%m%s ') + '. Zip ' 

The Python3.0 code is as follows:

Target_dir = ' E:\\backup ' 
target = target_dir + os.sep + time.strftime ('%y%m%d%h%m%s ') + '. Zip ' 

Os.sep's function is to automatically identify the operating system, give a different separator, Windows on the \\,linux is/, the principle is clear, the function is also very good, but the author's example. Only one place uses the OS.SEP, the other place is still the old writing AH (e:\\)

8.
You can declare a class method using the @ modifier:

  @classmethod 
  def howmany (Klass): 
    ' Prints the current population. ' 
    Print (' We have {0:d} robots. ') Format (robot.population)) 

9.
An abstract method that can be declared as an abstract class in a metaclasses way

From ABC import * 

class Schoolmember (Metaclass=abcmeta): 
  "represents any school member." 
  def __init__ (self, Name, age): 
    self.name = name 
    Self.age = Age 
    Print (' (initialized Schoolmember: {0}) '. Format (self.name)) 

  @abstractmethod 
  def tell (self): "' Tell me 
    details. 
'" Print (' Name: ' {0} ' age: ' {1} ' '. Format (Self.name, self.age), end= "") 
    #pass 

10.
There are two additional types of file reading and writing: text (' t ') binary (' B ').

11. Put the operation of the open file into the use with statement modified method, the book said the advantage is that we are more focused on file operations, so that the code does not look messy, this article can not fully understand the benefits of with. Present example code for everyone to refer to:

#!/usr/bin/python 
# Filename:using_with.py from 
contextlib import context 
@contextmanager 
def Opened (filename, mode= "R") 
  f = open (filename, mode) 
  try: 
    yield F 
  finally: 
    f.close () 

with Opened ("Poem.txt") as F: 
  for line in F: 
    print (line, end= ') 

12.python3.0 added logging module, giving me a feeling similar to the log4j in Java, looking directly at the code:

Import OS, platform, logging 
if Platform.platform (). StartsWith (' Windows '): 
logging_file = Os.path.join ( Os.getenv (' homedrive '), 
os.getenv (' HomePath '), ' test.log ') 
else: 
  logging_file = Os.path.join ( Os.getenv (' home '), ' Test.log ') 
logging.basicconfig ( 
  level=logging. DEBUG, 
  format= '% (asctime) s:% (levelname) s:% (message) s ', 
  filename = logging_file, 
  FileMode = ' W ', 
) 
Logging.debug ("Start of") 
Logging.info ("doing something") 
logging.warning ("Dying Now")

Hopefully this article will help you understand the Python3.0 and python2.x some of the different uses.

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.