The difference between python2.7 and Python3.5 __python

Source: Internet
Author: User
Tags integer division
1. Performance Py3.0 running Pystone benchmark speed is 30% slower than Py2.5. Guido that Py3.0 has great optimization space, and can achieve good results in string and plastic operation. Py3.1 performance is 15% slower than Py2.5, and there is a lot of room for improvement. 2. Encoding the py3.x source file uses Utf-8 encoding by default, which makes the following code legal:     >>> China = ' Chinese '     >>> Print (China)     Chinese 3. Syntax 1) Remove the <&gt, all using!= 2 to remove the ', all use Repr () 3) keyword to add as and with, as well as True,false,none 4) integer division return floating-point number, to get the integer result, please//5 to join the nonlocal statement. Use noclocal x to directly assign peripheral (NON-GLOBAL) variable 6 to remove the print statement and add the print () function to achieve the same functionality. There is also the EXEC statement, which has been changed to exec () function    For example:      2.x:print "The answer is", 2*2 &NBSP;&NBSP;&NBSP;&NB Sp 3.x:print ("The answer is", 2*2)      2.x:print x,                                # Use a comma to end a newline      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)    & nbsp;                       # 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 and throw the TypeError instead of returning the BOOL value 8, the input function changes, deletes the raw_input, and replaces it with input:    2.x:guess = Int (raw_input (' Enter an integer: ') # Read the keyboard input method    3.x:guess = Int (input (' Enter an integer: ') 9) Remove the tuple parameter unpack. Cannot def (A, (b, c)):p This defines a function of 10) The new 8-character variable, and modifies the OCT () function accordingly.    2.X in the following way:      >>> 0666      438       >>> Oct (438)      ' 0666 '    3.X in this way:      >>> 0666      Syntaxerror:invalid token (<pyshell#63>, line 1)      >> > 0o666      438      >>> Oct (438)      ' 0o666 ' 11 adds 2 literal and bin () functions     >>> Bin (438)     ' 0b110110110 '      >>> _438 = ' 0b110110110 '     >>> _438     ' 0b110110110 ' 12) extends the iterative solution of the package. In py3.x, A, b, *rest = seq and *rest, a = seq are all legitimate, requiring only two points: Rest is the list object and SEQ is iterative. 13 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) # No parameters call Super ()     >>> D (8)     C 8     <__main__. D object at 0x00d7ed90> 14) New Metaclass syntax:     class Foo (*bases, **kwds):        Pass 15) supports 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, world! Class decorator can be used to play the big game of civet cats in exchange for the prince. For more, see Pep 3129 4. String and byte string 1) Now the string has only one type of STR, but it's almost the same as the 2.x version of Unicode. 2 for the byte string, see "Data Type" 2nd Item 5. Data Type 1 py3.x The long type, now only an integer--int, but it behaves like 2. The x version of long 2 adds the bytes type, corresponding to 2. X version of the eight-bit string that defines a bytes literal as follows:     >>> B = B '  & '     >>> type (b) nbsp;  <type ' bytes ' > 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     ' i '      >>> B1 = S.encode ()     >>> B1     B ' dict ' 3 the. keys (),. Items, and. Values () methods return iterators, and functions such as the previous iterkeys () are discarded. Also remove the Dict.has_key () and replace it with in. 6. Object-oriented 1 introduces an 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 & nbsp;   iterable     iterator     keysview     Mapping  & nbsp;  mappingview     mutablemapping     mutablesequence     Mutableset     namedtuple     Sequence     Set     sized & nbsp;   valuesview     __all__     __builtins__     __doc__     __file__     __name__     _abcoll     _itemgetter     _sys     defaultdict     deque in addition, Numeric types are also 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 4 of the iterator to add @abstractmethod and @abstractproperty two Decorator, it is more convenient to write abstract methods (properties). 7. Exception 1) So the exception is inherited from the Baseexception, and Stardarderror 2 is removed from the sequence behavior of the exception class and the. Message attribute 3 is replaced args raise with raise Exception (Exception). Args Syntax 4 captures the syntax change of an exception and introduces the AS keyword to identify an exception instance in Py2.5:     >>> try:     ...     Raise Notimplementederror (' ERROR ')     ... except Notimplementederror, error:     ...    print error.message     ...     error in Py3.0:     & Gt;>> 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 Change 1) Remove the Cpickle module, You can use the Pickle module instead. In the end we will have a transparent and efficient module. 2 removed IMAGEOP module 3) removed Audiodev, Bastion, bsddb185, exceptions, Linuxaudiodev, MD5, Mimewriter, Mimify, Popen2, Rexec, Sha, Stringold, Strop, Sunaudiodev, Timing and Xmllib Module 4 Remove the BSDDB module (published separately, available from http://www.jcea.es/programacion/ Pybsddb.htm get) 5 removed the new Module 6 Os.tmpnam () and the Os.tmpfile () function was moved to the Tmpfile module under 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 obtain a list using range (), you must explicitly call:      >>> list (range)     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2) bytes objects cannot be hashed and do not support B.lower (), B.str The IP () and B.split () methods, but both can use 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 () functions are removed and can now be replaced with hasattr (). Hasattr () syntax such as: hasattr (String, ' __name__ ') 4) string.letters and related. Lowercase and. Uppercase are removed, please use String.ascii_Letters 5) If x < y cannot be compared, throw TypeError exception. The 2.x version is 6 of the returned pseudo random Boolean value __getslice__ series members are discarded. A[I:J] conversion to a.__getitem__ (Slice (i, j)) or __setitem__ and __delitem__ invoke 7) The file class is discarded in Py2.5:     >> > File     <type ' file ' > in py3.x:     >>> file     Traceback (most recent):     File "<pyshell#120>", line 1, in <module> &NBSP;&NBSP;&N bsp;    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.