10 major differences between Python2 and Python3

高洛峰
Release: 2016-10-19 16:26:58
Original
969 people have browsed it

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.

2. Encoding

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

>>>>China = 'china'

>>> print (China)

china

3. Grammar

1) Remove and use !=

2) Remove `` and use repr() for all

3) Add as and with keywords, as well as 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 exec()

4. Function

1) The print statement has been replaced by the print() function. Keyword parameters can be used to replace the old print special syntax. For example:

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

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

Old: print x, #Use a comma at the end to disable line breaks

New: print (x, end=" ") # Use spaces to replace lines

Old: print # Output new lines

New: print() # Output new lines

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

2) Changed the behavior of sequential operators, such as x

3) Input function changes Now:

Old:

guess = int(raw_input('Enter an integer : ')) #How to read keyboard input

New:

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

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

5) New octal word variable, the oct() function has been modified accordingly. The way for 2.x is as follows

>>> 0666

438

>>> oct(438)

'0666'

3.0 is like this:

>>> 0666

SyntaxError: invalid token (, line 1 )

>>> 0o666

438

>>> oct(438)

'0o666'

6) Added binary literal and bin() function

>>>> bin(438)

'0b110110110'

>>> _438 = '0b110110110'

>>> _438

'0b110110110'

7) Extended iterable unpacking. In Py3.0, a, b, *rest = seq and *rest, a = seq are legal, and only require two points: rest is a list object and seq is iterable

8) New super() , you can no longer pass parameters to super()

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

8

<__main__.d>9) New The metaclass syntax

class Foo(*bases, **kwds):

pass

10) supports class decorator. The usage is the same as the 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 the big trick of changing the civet cat to the prince. For more information, please refer to PEP 3129

5, Strings and ByteStrings

1) Now strings only have one type, 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"

6. Data Type

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

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

>>> 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. The .keys(), .items, and .values() methods of dict return iterators, and the previous iterkeys() and other functions have been abandoned. Also removed is dict.has_key(), replace it with in

7, 7. Object-oriented

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

2) Container classes and iterator classes are ABCs, 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

Mu tableSequence

MutableSet

NamedTuple

Sequence

Set

Sized

ValuesView

__all__

__builtins__

__doc__

__file__

__name__

_abcoll

_itemgetter

_sys

defaultdict

deque

In addition, numerical 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 decorators, @abstractmethod and @abstractproperty, are added , it is more convenient to write abstract methods (properties)

8. Exceptions

1) So 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) replaces 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: #Note this as

print(str(error))

Error

5) exception chain, because __context__ has not been implemented in version 3.0a1, this I won’t talk about it

9. Module changes

• The cPickle module has been removed and can be replaced by the pickle module. 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 the bsddb module (released separately, available from http://www.jcea.es/programacion/pybsddb.htm)

• Removed the new module

• os.tmpnam() and os.tmpfile( ) function has been 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, 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) The bytes object cannot hash, nor does it support b.lower( ), b.strip() and b.split() methods, but for the latter two, you can use b.strip(b' ntrf') 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 all been removed

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

5) If x

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

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

>>> file


in Py3.0:

>>> file

Traceback (most recent call last):

File "", line 1, in

file

NameError: name 'file' is not defined


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!