Home >Backend Development >Python Tutorial >The difference between python3 and python2.7

The difference between python3 and python2.7

高洛峰
高洛峰Original
2016-11-23 09:10:321632browse

If you search, you will know that python has two main versions, python2 and python3, but python is different from other languages ​​and is backward compatible. python3 is not backward compatible, but most components and extensions are based on For python2, let’s summarize the differences between python2 and python3.

1. Performance

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

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

2. Encoding

Py3. (China)

china

3. Grammar

1) Remove <>, all use !=

2) Remove ``, all use repr()

3) Add keywords as and with, and True, False, None

4) Integer division returns a floating point number. To get an integer result, please use //

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

6) Remove the print statement and add the print() function to achieve the same function. The same is true for the exec statement, which 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.

2. 3.

2.

7) Change The behavior of the sequential operator, such as x

8) The input function has been changed, raw_input has been deleted and replaced with input:

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

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

9) Remove tuple parameter unpacking. The function cannot be defined like def(a, (b, c)):pass

10) The new octal word variable, the oct() function has been modified accordingly.

2.

3.X like this:

 >> ;> 0666

SyntaxError: invalid token (, line 1)

>>> 0o666

438

; oct(438)

'0o666'

11) Added binary literals and bin() function

>>> bin(438)

'0b110110110'

>>> _438 = '0b110110110'

> >> _438

'0b110110110'

12) Extended iterable unpacking. In Py3. U13) The new super () can no longer pass the parameters of the super (),

& gt; & gt; & gt; class c (object):

def __init __ (seld, a):

print ('c (' c ('c (' c ('c ', a)

  >>> class D(C):

            def __init(self, a):

. Super () .__ init __ (a) # No parameter call super ()

& gt; & gt; d (8)

c 8

& lt; __. D object at 0x00d7ed90 & gt;

14) Syntax:

class Foo(*bases, **kwds):

pass

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

                                                                                                                                                                                                                                                      _a.print = print_func

              return cls_a

>>> @foo

class C(object):

pass

>>> C().print()

Hello, world!

class decorator can be used to play Playing the civet cat trick to exchange for the prince. For more information, please refer to PEP 3129

4. Strings and byte strings

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

2) For byte strings, please refer to the 2nd item of "Data Type"

5. Data Type

1) Py3.X has removed the long type, and now there is only one integer type - int, but It behaves like long in version 2.X

2) A new bytes type is added, corresponding to the octet string in version 2. = b'china'

>>> type(b)

Str objects and bytes objects can use .encode() (str -> bytes) or .decode () (bytes -> str) method mutual conversion.

>>> s = b.decode()

>>> s

t;> > b1

b'china'

3) dict's .keys(), .items and .values() methods return iterators, while the previous iterkeys() and other functions have been abandoned. Also removed is

dict.has_key(), replace it with in

6. Object-oriented

1) Introduce abstract base classes (Abstract Base Classes, ABCs).

2) Container classes and iterator classes are ABCsized, so there are many more types in the cellections module than in Py2.5.

>>> import collections

>>> print('n'.join(dir(collections)))

Callable

Container

Hashable

ItemsView

Iterable

Iterator

KeysView

Mapping

MappingView

MutableMapping

MutableSequence

MutableSet

NamedTuple

Sequ ence

Set

Sized

ValuesView

__all__

__builtins__

__doc__

__file__

__

_abcoll

_itemgetter

_sys

defaultdict

deque

In addition, numeric types are also ABCsized. On these two points, see PEP 3119 and PEP 3141.

3) The next() method of iterator is renamed to __next__(), and the built-in function next() is added to call the __next__() method of iterator

4) Two @abstractmethod and @abstractproperty are added decorator, it is more convenient to write abstract methods (properties).

7. Exceptions

1) All exceptions are inherited from BaseException, and StardardError is deleted

2) The sequence behavior and .message attribute of the exception class are removed

3) Use raise Exception(args) instead of raise Exception, args Syntax

4) Syntax changes for catching exceptions, the as keyword is introduced to identify exception instances, in Py2.5:

>>> try:

... raise NotImplementedError('Error')

... except NotImplementedError, error:

... print error.message

...

Error

in Py3.0:

>>> try:

          raise NotImplementedError('Error') 

        except NotImplementedError as error: #注意这个as 

          print(str(error)) 

    Error 

5)异常链,因为__context__在3.0a1版本中没有实现 

8. Module changes

1) The cPickle module has been removed and can be replaced by the pickle module. 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 module

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

5) Removed the new module

6) os.tmpnam () and os.tmpfile() functions have been moved to the tmpfile module

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

9. Others

1) xrange() is renamed to range(). If you want to use range() to get a list, you must call it explicitly:

>>> list(range(10))

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

2) Bytes objects cannot hash, nor do they support b .lower(), b.strip() and b.split() methods, but for the latter two you can use b.strip(b'

ntr f') and b.split(b' ') to achieve the same purpose

3) zip(), map() and filter() all return iterators. The apply(), callable(), coerce(), execfile(), reduce() and reload

() functions have been removed

Now you can use hasattr() to replace callable(). hasattr() The syntax is such as: hasattr(string, '__name__')

4) string.letters and related .lowercase and .uppercase are removed, please use string.ascii_letters instead etc.

5) If x < y cannot Compare, throw TypeError exception. Version 2.x returns pseudo-random Boolean values ​​

6) The __getslice__ series members are abandoned. a[i:j] is converted to a.__getitem__(slice(I, j)) or __setitem__ and

__delitem__ is called according to the context

7) The file class is deprecated, in Py2.5:

> >> file

in Py3. 120>", line 1, in

                                                                                                                                                name 'file'

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn