10 big differences between Python2 and Python3

Source: Internet
Author: User
Tags integer division
1. Performance

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

2. Encoding

Py3.0 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 exec ()

4. Functions

1) The print statement is replaced by the print () function, which replaces the old print special syntax with the keyword parameter. For example:

Old:print "The answer is", 2*2

New:print ("The answer is", 2*2)

Old:print x, # Stop line wrapping with a comma end

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

Old:print # Output New Line

New:print () # Output New Line

Old:print >>sys.stderr, "Fatal error"

New:print ("Fatal error", File=sys.stderr)

Old:print (x, y) # output repr ((x, y))

New:print ((x, y)) # is different from print (x y)!

2) Change the behavior of the order operator, e.g. X<><><>

3) The input function has changed:

Old:

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

New:

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

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

5) The new 8 binary character variable, the OCT () function is modified accordingly. 2.x in the following way

>>> 0666

438

>>> Oct (438)

' 0666 '

3.0 this:

>>> 0666

Syntaxerror:invalid token (, line 1)

>>> 0o666

438

>>> Oct (438)

' 0o666 '

6) added 2 binary literals and bin () functions

>>> Bin (438)

' 0b110110110 '

>>> _438 = ' 0b110110110 '

>>> _438

' 0b110110110 '

7) An extensible iterative solution package. In Py3.0, A, b, *rest = seq and *rest, a = seq is legal and requires only two points: Rest is a list object and SEQ is an iterative

8) 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) #无参数调用super ()

>>> D (8)

C 8

<__main__.d>

9) New Metaclass syntax

Class Foo (*bases, **kwds):

Pass

10) 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,

Class decorator can be used to play civet cats for the great tricks of the prince. See Pep 3129 for more

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

6. Data type

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

2) New bytes type, corresponding to the 2.x version of the eight-bit string, the method of defining a bytes literal is as follows:

>>> B = B ' China '

>>> type (b)


3) Str objects and Bytes objects can be converted using. Encode () (str, bytes) or. Decode () (bytes-STR) methods

>>> s = B.decode ()

>>> s

' China '

>>> B1 = S.encode ()

>>> B1

B ' China '

4) 1. The Dict keys (),. Items, and. Values () methods return iterators, and functions such as the previous iterkeys () are discarded. Also remove Dict.has_key (), replace it with in

7, 7, object-oriented

1) 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, more convenient to write abstract methods (attributes)

8. Abnormal

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) The exception chain, because __context__ in the 3.0A1 version has not been implemented, this is not said

9. Module changes

• Removing the Cpickle module, you can use the Pickle module instead. Eventually we will have a transparent and efficient module.

• Removed Imageop module

• Removed Audiodev, Bastion, bsddb185, exceptions, Linuxaudiodev, MD5, Mimewriter, Mimify, Popen2, rexec, sets, Sha, Stringold, Strop, Sunaudiodev, timing and Xmllib modules

• Removed BSDDB module (released separately, can be obtained from http://www.jcea.es/programacion/pybsddb.htm)

• Removed new module

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

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

10. 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) Bytes object can not hash, also does not support B.lower (), B.strip () and B.split () method, but for the latter two may 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. The Apply (), callable (), coerce (), execfile (), reduce (), and reload () functions are removed

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] a.__getitem__ (Slice (i, j)) or __setitem__ and __delitem__ based on context conversion

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

>>> file


In the Py3.0:

>>> file

Traceback (most recent):

File "", Line 1, in

File

Nameerror:name ' file ' is not defined

  • 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.