Python3 and python2.7 respectively

Source: Internet
Author: User
If you search for python3 and python2.7 respectively, you will know that python has two major versions: python2 and python3, but python is backward compatible with other languages, python3 is not backward compatible, but most components and extensions are based on python2. The difference between python2 and python3 is summarized below.

1. performance

Py3.0 runs pystone benchmark 30% slower than Py2.5. Guido believes that Py3.0 has a huge space for optimization, which can be used for string and integer operations.

To achieve good optimization results.

Py3.1 performance is 15% slower than Py2.5, and there is still much room for improvement.

2. encoding

The Py3.X source code file uses UTF-8 encoding by default, which makes the following code legal:

>>> China = 'China'

>>> Print (China)

China

3. Syntax

1) remove <>, switch to all! =

2) remove ''and use repr () instead ()

3) add the as and with keywords, and add True, False, None

4) the integer division function returns a floating point number. to obtain the integer result, use //

5) add the nonlocal statement. You can use noclocal x to directly assign peripheral (non-global) variables.

6) remove the print statement and add the print () function to implement the same function. The exec statement has been changed to the exec () function.

For example:

2. X: print "The answer is", 2*2

3. X: print ("The answer is", 2*2)

2. X: print x, # use a comma to end the line break.

3. X: print (x, end = "") # use spaces to replace line breaks

2. X: print # output New Line

3. X: print () # output a new line

2. X: print> sys. stderr, "fatal error"

3. X: print ("fatal error", file = sys. stderr)

2. X: print (x, y) # output repr (x, y ))

3. X: print (x, y) # unlike print (x, y )!

7) changes the behavior of sequence operators, such as x

8) the input function is changed. raw_input is deleted and replaced by input:

2. X: guess = int (raw_input ('Enter an integer: ') # How to Read keyboard input

3. X: guess = int (input ('Enter an integer :'))

9) remove the productkey parameter from the package. You cannot define a function like def (a, (B, c): pass.

10) The new octal variable modifies the oct () function accordingly.

The method of 2.x is as follows:

>>> 0666

438

>>> Oct (438)

'123'

3. X:

>>> 0666

SyntaxError: invalid token ( , Line 1)

>>> 0o666

438

>>> Oct (438)

'0o666'

11) added the binary literal and bin () functions.

>>> Bin( 438)

'0b110110110'

>>> _ 438 = '0b110110110'

>>> _ 438

'0b110110110'

12) scalable and iterative unpacking. In Py3.X, a, B, * rest = seq and * rest, a = seq are both valid and only two points are required: rest is list

Objects and seq can be iterated.

13) the new super () can no longer pass parameters to super,

>>> Class C (object ):

Def _ init _ (self, ):

Print ('C',)

>>> Class D (C ):

Def _ init (self, ):

Super (). _ init _ (a) # super () called without parameters ()

>>> D (8)

C 8

<__ Main _. D object at 0x00D7ED90>

14) new metaclass syntax:

Class Foo (* bases, ** kwds ):

Pass

15) supports class decorator. The usage is the same as that of the decorator function:

>>> Def foo (cls_a ):

Def print_func (self ):

Print ('Hello, world! ')

Cls_a.print = print_func

Return cls_a

>>> @ Foo

Class C (object ):

Pass

>>> C (). print ()

Hello, world!

Class decorator can be used to play the big tricks of the CAPTCHA. For more information, see PEP 3129.

4. string and byte string

1) currently, only one type of string is available, but it is almost the same as unicode in 2.x.

2) for a byte string, see the 2nd entries in "data type ".

5. data type

1) Py3.X removes the long type, and now there is only one integer -- int, but it acts like the long type

2) the bytes type is added, which corresponds to the 8-bit string of the 2.x version. The following describes how to define a bytes literal:

>>> B = B 'China'

>>> Type (B)

The str object and bytes object can be converted using the. encode () (str-> bytes) or. decode () (bytes-> str) method.

>>> S = B. decode ()

>>> S

'China'

>>> B1 = s. encode ()

>>> B1

B 'china'

3) dict's. keys (),. items, and. values () methods return to the iterator, while previous iterkeys () and other functions are discarded. Also removed

Dict. has_key (), replace it with in.

6. object-oriented

1) introduce abstract Base Classes (Abstraact Base Classes, ABCs ).

2) the container class and iterator class are ABCs, so the types in the cellections module are much more than Py2.5.

>>> Import collections

>>> Print ('\ n'. join (dir (collections )))

Callable

Container

Hashable

ItemsView

Iterable

Iterator

KeysView

Mapping

MappingView

MutableMapping

MutableSequence

MutableSet

NamedTuple

Sequence

Set

Sized

ValuesView

_ All __

_ Builtins __

_ Doc __

_ File __

_ Name __

_ Abcoll

_ Itemgetter

_ Sys

Defaultdict

Deque

In addition, the value type is also ABCs. For more information, see PEP 3119 and PEP 3141.

3) the next () method of the iterator is changed to _ next _ (), and the built-in function next () is added to call the _ next _ () method of the iterator.

4) added two decorator: @ abstractmethod and @ abstractproperty, which makes it easier to compile abstract methods (attributes.

7. Exceptions

1) The exceptions are inherited from BaseException and the StardardError is deleted.

2) remove the sequence behavior and. message attributes of the exception class

3) use raise Exception (args) instead of raise Exception. args syntax

4) capture abnormal syntax changes and introduce the as keyword to identify abnormal instances. in Py2.5:

>>> Try:

... Raise NotImplementedError ('error ')

... Handle T NotImplementedError, error:

... Print error. message

...

Error

In Py3.0:

>>> Try:

Raise NotImplementedError ('error ')

Failed T NotImplementedError as error: # pay attention to this

Print (str (error ))

Error

5) exception chain, because _ context _ is not implemented in version 3.0a1

8. module changes

1) the cPickle module is removed and can be replaced by the pickle module. In the end, we will have a transparent and efficient module.

2) removed the imageop module.

3) removed audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2,

Rexec, sets, sha, stringold, strop, sunaudiodev, timing, and xmllib modules

4) removed the bsddb module (released separately, available at http://www.jcea.es/programacion/pybsddb.htm)

5) removed the new module.

6) the OS. tmpnam () and OS. tmpfile () functions are moved to the tmpfile module.

7) The tokenize module now uses bytes to work. The main entry point is not generate_tokens, but tokenize. tokenize ()

9. others

1) xrange () is renamed to range (). to use range () to obtain a list, you must explicitly call:

>>> List (range (10 ))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2) bytes objects cannot be hashed or B. lower (), B. strip () and B. the split () method, but the latter two can use B. strip (B'

\ N \ t \ r \ f') and B. split (B '') to achieve the same purpose

3) both zip (), map (), and filter () return the iterator. Apply (), callable (), coerce (), execfile (), reduce (), and reload

() All functions are excluded

Now you can use hasattr () to replace the syntax of callable (). hasattr (), such as hasattr (string, '_ name __')

4) string. letters and related. lowercase and. uppercase are removed. use string. ascii_letters and so on.

5) if x <y cannot be compared, a TypeError exception is thrown. 2. version x returns a pseudo-random boolean value.

6) _ getslice _ Series members are discarded. A [I: j] is converted to a. _ getitem _ (slice (I, j) or _ setitem _ and

_ Delitem _ call

7) the file class is discarded. in Py2.5:

>>> File

In Py3.X:

>>> File

Traceback (most recent call last ):

File" ", Line 1, in

File

NameError: name 'file' is not defined

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.