python3.x and python2.x The difference introduction _python

Source: Internet
Author: User
Tags integer division

1. Performance
The Py3.0 runs Pystone benchmark 30% slower than Py2.5. Guido that Py3.0 has a great space for optimization, in string and plastic operations can be
To achieve good optimization results.
Py3.1 performance is 15% slower than Py2.5, and there is a lot of room for improvement.

2. Code
The py3.x source file uses Utf-8 encoding by default, which makes the following code legal:
>>> China = ' Chinese '
>>>print (China)
The

3. Grammar
1) Remove the <>, and switch to!=.
2) Remove ", all switch to REPR ()
3 keywords add as and with, and True,false,none
4) Integer division returns the floating-point number, to get the integer result, use//
5) Add the nonlocal statement. External (Non-global) variables can be assigned directly using noclocal x
6 Remove the Print statement and add the print () function to achieve the same function. There is also the EXEC statement, which has been changed to 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 wrapping with 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 changes the behavior of the order operator, such as X<y, when the x and Y types do not match, throw the TypeError instead of returning the bool value immediately
8 input function changed, delete raw_input, replace with input:
2.x:guess = Int (raw_input (' Enter an Integer: ') # Read keyboard Input Method
3.x:guess = Int (input (' Enter an Integer: '))

9) to remove the tuple parameter solution package. Cannot def (A, (b, c)):p This defines a function
10 The new 8-character variable, the OCT () function is modified accordingly.
The 2.X approach is as follows:
>>> 0666
438
>>> Oct (438)
' 0666 '
3.X this way:
>>> 0666
Syntaxerror:invalid token (&LT;PYSHELL#63&GT;, line 1)
>>> 0o666
438
>>> Oct (438)
' 0o666 '
11 added 2 literal and bin () functions
>>> Bin (438)
' 0b110110110 '
>>> _438 = ' 0b110110110 '
>>> _438
' 0b110110110 '
12) Scalable iterative solution. In py3.x, A, b, *rest = seq and *rest, a = seq are all legitimate, requiring only two points: rest is the list
Objects and SEQ can be iterated.
13 The new super (), can no longer give super () pass parameters,
>>> class C (object):
def __init__ (Self, a):
Print (' C ', a)
>>> class D (C):
def __init (Self, a):
Super (). __init__ (a) # call super () without parameters
>>> D (8)
C 8
<__main__. D Object at 0x00d7ed90>
14 The new Metaclass syntax:
Class Foo (*bases, **kwds):
Pass
15) Support 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, world!.
Class decorator can be used to play the big game of civet cats in exchange for the prince. more see pep 3129

4. Strings and Byte strings
1 Now the string has only one type of STR, but it is almost the same as the 2.x version of Unicode.
2 for the byte string, see the 2nd Item of "Data type"

5. Data type
1 py3.x removes the long type and now has only one integral type--int, but behaves like 2. X version of Long
2 new bytes type, corresponding to 2. X version of the eight-bit string, which defines a bytes literal method as follows:
>>> B = B ' It '
>>> type (b)
<type ' bytes ' >
The Str object and the Bytes object can be converted to each other using the. encode () (str-> bytes) or. Decode () (bytes-> str) method.
>>> s = B.decode ()
>>> s
' I '
>>> B1 = S.encode ()
>>> B1
B ' I '
3 The Dict. Keys (),. Items, and. Values () methods return iterators, and functions such as the previous iterkeys () are discarded. And also removed from the
Dict.has_key (), replace it with in.

6. Object-oriented
1) Introduce abstract base class (Abstraact base Classes,abcs).
2 the container class and iterator class are ABCs, so the type of cellections module is much more than 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 ABCs. See Pep 3119 and Pep 3141 for these two points.
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, it is more convenient to write abstract methods (properties).

7. Abnormal
1 so the exception is inherited from Baseexception and deleted by Stardarderror
2 Removes the sequence behavior of the exception class and the. Message property
3) Replace raise Exception with raise Exception (args), args syntax
4 Capture the syntax change of the exception, 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 3.0A1 version

8. Module changes
1 Remove the Cpickle module, you can use the Pickle module instead. In the end we will have a transparent and efficient module.
2 Remove Imageop Module
3) removed Audiodev, Bastion, bsddb185, exceptions, Linuxaudiodev, MD5, Mimewriter, Mimify, Popen2,
Rexec, sets, Sha, Stringold, Strop, Sunaudiodev, timing and Xmllib modules
4 Remove BSDDB module (separate release, can be obtained from http://www.jcea.es/programacion/pybsddb.htm)
5) Remove new module
6) 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 use range () to obtain a list, you must explicitly call:
>>> List (range (10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2) The Bytes object cannot be hashed and does not support B.lower (), B.strip (), and B.split () methods, but for the latter two can be used B.strip (b '
\n\t\r \f ') and b.split (b ') to achieve the same purpose
3) Zip (), map (), and filter () return the iterator. The Apply (), callable (), coerce (), execfile (), reduce (), and reload
() function is 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, please use string.ascii_letters, etc.
5 if x < y cannot be compared, throw TypeError exception. The 2.x version is a
6) that returns a pseudo random Boolean value __getslice__ series members are discarded. A[I:J] The file class is discarded based on the context conversion to a.__getitem__ (Slice (i, j)) or __setitem__ and
__delitem__ calls
7), in Py2.5:
     >>> file
    <type ' file '
in py3.x:
    >>> File
    Traceback (most recent call last):
    file ' <pyshell#120> ', line 1, In <module>
       file
    nameerror:name ' file ' isn't 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.