The distinction between Python3 and python2.7

Source: Internet
Author: User
Tags integer division
You'll know that Python has two major versions, Python2 and Python3, but Python is different from other languages, backwards-compatible, Python3 is backwards-compatible, but most components and extensions are Python2-based, Here's a summary of the differences between Python2 and Python3.

1. Performance

PY3.0 runs Pystone benchmark slower than Py2.5 by 30%. Guido that Py3.0 has great space for optimization, and can be used in string and shaping operations.

To achieve a good result of optimization.

Py3.1 performance is 15% slower than Py2.5, and there's a lot of room for improvement.

2. Encoding

py3.x source files use utf-8 encoding by default, which makes the following code legal:

>>> Chinese = ' China '

>>>print (China)

China

3. Syntax

1) removal of <>, all use! =

2) Remove ', all switch to REPR ()

3) keywords join as and with, and True,false,none

4) integer division return floating-point number, to get the integer result, use//

5) Add the nonlocal statement. Use noclocal x to assign a peripheral (non-global) variable directly

6) Remove the print statement and add the print () function to achieve the same functionality. The same 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, # Stop line wrapping with a comma end

3.x:print (X, end= "") # Use a space instead of a newline

2.x:print # Output New Line

3.x:print () # Output 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)) # is different from print (x y)!

7) Change the behavior of the order operator, such as X<y, when the x and Y types do not match, throw TypeError instead of returning the immediately bool value

8) Input function changed, delete raw_input, use input instead:

2.x:guess = Int (raw_input (' Enter an integer: ') # Method for reading keyboard input

3.x:guess = Int (input (' Enter an Integer: '))

9) Remove the tuple parameter unpacking. Cannot def (A, (b, c)):p the definition of a function like the

10) The new 8 binary character variable, the OCT () function is modified accordingly.

The 2.X approach is as follows:

>>> 0666

438

>>> Oct (438)

' 0666 '

3.X this:

>>> 0666

Syntaxerror:invalid token (<PYSHELL#63>, line 1)

>>> 0o666

438

>>> Oct (438)

' 0o666 '

11) Added 2 binary literals and bin () functions

>>> Bin (438)

' 0b110110110 '

>>> _438 = ' 0b110110110 '

>>> _438

' 0b110110110 '

12) An extensible iterative solution package. In py3.x, A, b, *rest = seq and *rest, a = seq is legal and requires only two points: rest is a list

The object and the SEQ are iterative.

13) New super (), can no longer give super () parameters,

>>> class C (object):

def __init__ (Self, a):

Print (' C ', a)

>>> class D (C):

def __init (Self, a):

Super (). __init__ (a) # no parameter call super ()

>>> D (8)

C 8

<__main__. D Object at 0x00d7ed90>

14) New Metaclass syntax:

Class Foo (*bases, **kwds):

Pass

15) Support class decorator. Usage is the same as function decorator:

>>> 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 civet cats for the great tricks of the prince. See Pep 3129 for more

4. Strings and Byte strings

1) Now the string is only one type of STR, but it is almost the same as the 2.x version of Unicode.

2) for the byte string, refer to the 2nd item in the data type

5. Data type

1) py3.x removed the long type and now has only one integer--int, but it behaves like 2. X version of Long

2) added the bytes type, corresponding to 2. X version of the eight-bit string, define a bytes literal method as follows:

>>> B = B ' China '

>>> type (b)

<type ' bytes ' >

str objects and Bytes objects can be converted using the. encode () (str-bytes) or. Decode () (bytes-str) methods.

>>> s = B.decode ()

>>> s

' China '

>>> B1 = S.encode ()

>>> B1

B ' China '

3) Dict. Keys (),. Items, and. Values () methods return iterators, and functions such as the previous iterkeys () are discarded. And it's also removed.

Dict.has_key (), replace it with in.

6. Object-oriented

1) Introduce abstract base class (Abstraact base Classes,abcs).

2) the container class and the iterator class are ABCs, so the type in the Cellections module is much more than the 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, numeric types are also ABCs. For these two points, see Pep 3119 and Pep 3141.

3) The next () method of the iterator is renamed __NEXT__ () and adds the built-in function next () to invoke the __next__ () method of the iterator

4) added @abstractmethod and @abstractproperty two decorator, writing abstract methods (attributes) more convenient.

7. Exceptions

1) So exceptions are inherited from Baseexception and deleted Stardarderror

2) removed the sequence behavior of the exception class and the. Message property

3) Replace raise Exception with raise Exception (args), args syntax

4) Catch exception syntax change, introduce the AS keyword to identify the exception instance, in Py2.5:

>>> Try:

... raise Notimplementederror (' Error ')

... except Notimplementederror, error:

... print Error.message

...

Error

In the Py3.0:

>>> Try:

Raise Notimplementederror (' Error ')

Except Notimplementederror as error: #注意这个 as

Print (str (error))

Error

5) exception chain, because __CONTEXT__ is not implemented in the 3.0A1 version

8. Module changes

1) Remove the Cpickle module, you can use the Pickle module instead. Eventually we will have a transparent and efficient module.

2) removed 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 BSDDB module (released separately, can be obtained from http://www.jcea.es/programacion/pybsddb.htm)

5) removed new module

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

7) Tokenize module now works with bytes. The main entry point is no longer generate_tokens, but Tokenize.tokenize ()

9. Other

1) xrange () renamed to Range (), to get a list using range (), you must explicitly call:

>>> List (range (10))

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

2) The Bytes object cannot be hashed, nor does it support the B.lower (), B.strip (), and B.split () methods, but for the latter two you 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 iterators. and apply (), callable (), coerce (), execfile (), reduce (), and reload

() function has been removed.

You can now replace callable () with Hasattr (). Hasattr () syntax such as: hasattr (String, ' __name__ ')

4) String.letters and related. Lowercase and. Uppercase are removed, use string.ascii_letters, etc.

5) If x < y cannot be compared, throw an TypeError exception. The 2.x version returns a pseudo-random Boolean value

6) __GETSLICE__ series members were discarded. A[I:J] is converted from context to a.__getitem__ (slice (i, j)) or __setitem__ and

__DELITEM__ Call

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

>>> file

<type ' file ' >

In the py3.x:

>>> file

Traceback (most recent):

File "<pyshell#120>", line 1, in <module>

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.