10 major differences between Python2 and Python3

Source: Internet
Author: User
Tags integer division
Py3.0 runs pystonebenchmark 30% slower than Py2.5. Guido believes that Py3.0 has a huge space for optimization and can achieve good optimization results in string and integer operations. 1. performance

Py3.0 runs pystone benchmark 30% slower than Py2.5. Guido believes that Py3.0 has a huge space for optimization and can achieve good optimization results in string and integer operations.

2. encoding

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

4. Functions

1) the print statement is replaced by the print () function. you can use the keyword parameter to replace the special syntax of the old print statement. For example:

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

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

Old: print x, # use a comma to end to disable line feed

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

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) # unlike print (x, y )!

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

3) the input function has changed:

Old:

Guess = int (raw_input ('Enter an integer: ') # How to Read keyboard input

New:

Guess = int (input ('Enter an integer :'))

4) remove the productkey parameter from the package. Do not define functions like def (a, (B, c): pass

5) The new octal variable modifies the oct () function accordingly. 2. the method of x is as follows:

>>> 0666

438

>>> Oct (438)

'123'

3.0:

>>> 0666

SyntaxError: invalid token (, line 1)

>>> 0o666

438

>>> Oct (438)

'0o666'

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

>>> Bin( 438)

'0b110110110'

>>> _ 438 = '0b110110110'

>>> _ 438

'0b110110110'

7) scalable and iterative unpacking. In Py3.0, a, B, * rest = seq and * rest, a = seq are both valid and only two points are required: rest is a list object and seq can be iterated.

8) 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>

9) New metaclass syntax

Class Foo (* bases, ** kwds ):

Pass

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

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

5. 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 ".

6. Data types

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


3) str objects and bytes objects can be converted to each other using the. encode () (str-> bytes) or. decode () (bytes-> str) method.

>>> S = B. decode ()

>>> S

'China'

>>> B1 = s. encode ()

>>> B1

B 'china'

4) 1. dict's. keys (),. items, and. values () methods return to the iterator, while previous iterkeys () and other functions are discarded. Dict. has_key () is also removed. replace it with in.

7. object-oriented

1) 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 higher than those in 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 ).

8. exception

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 _ has not been implemented in version 3.0a1.

9. module changes

• Removed the cPickle module, which can be replaced by the pickle module. In the end, we will have a transparent and efficient module.

• Removed the imageop module.

• Removed audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2, rexec, sets, sha, stringold, strop, sunaudiodev, timing, and xmllib modules

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

• Removed the new module.

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

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

10. 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. The apply (), callable (), coerce (), execfile (), reduce (), and reload () functions are all removed

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 _ according to the context.

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

>>> File


In Py3.0:

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