Experience with Python 3.0

Source: Internet
Author: User
Tags integer division
Experience with Python 3.0

Welcome to reprint, print, distribution, etc., but cannot be used for commercial purposes, at any time must keep the full text complete, and the statement reproduced narcissistic butterfly blog (http://blog.csdn.net/lanphaday), thank you. In August 31, 2007, Python 3000's latest version, py3.0, finally released the first alpha version. Because version 3.0 is not compatible with version 2.x, py3.0 can be regarded as a new version of Py. This is a real event in the python community. Although final version of py3.0 will not be released until August, we can still see many new features of py3.0 from A1. now let's try it out. Download and installDownload the package at http://www.python.org/download/releases/3.0. The compressed source code package (50 MB) and Windows Installation Package (10 MB) are provided ). CompatibilityAs early as py3.0 was released, Guido said py3.0 was no longer compatible with py2.x. It seems that this is indeed the case. However, a "2to3" converter is provided so that developers can transfer the code of py2.x to py3.0. However, this version has not yet been officially released, and only the svn repository can be checkout. Address here: http://svn.python.org/view/sandbox/trunk/2to3/ PerformancePy3.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. EncodingThe py3.0 source code file uses UTF-8 encoding by default, which makes the following code Legal: >>> China = 'China' >>> print (China) China Syntax:1) Remove <>, switch to all! =. 2) Remove ''and use the Repr () (3) keyword to add as and. 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 the exec () function. 7) Remove the productkey parameter from the package. Do not define functions like Def (A, (B, c): Pass. (8) The new octal literal, And the OCT () function is modified accordingly. 2. X is like this: >>> 0666438 >>> OCT (438) '000000' 3. 0: >>> 0666 syntaxerror: Invalid token (<pyshell #63>, line 1) >>>> 0o666438 >> OCT (438) '0o666' 9) added the binary literal and bin () functions: >>> Bin (438) '0b110110110 '>>> _ 438 = '0b110110110' >>>> _ 438 '0b110110110 '10) 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. 11) the new super () can no longer pass parameters to super (), >>> class C (object): def _ init _ (self, ): print ('C', A) >>> Class D (c): def _ Init (self, A): Super (). _ init _ (a) # super ()> D (8) C 8 <__ main __. D object at 0x00d7ed90> 12) New metaclass Syntax: Class Foo (* bases, ** kwds): For details about pass, see pep 3115. 13) supports class decorator. Usage is the same as the decorator function: >>> def Foo (cls_a): def print_func (Self): Print ('hello, world! ') Cls_a.print = print_func return cls_a >>>@ fooclass C (object): Pass >>> C (). Print () Hello, world! Class decorator Can be used to play the big tricks of the CAPTCHA. For more information, see pep 3129. 14) for syntax changes of raise statements, see entries 3rd and 4 in the "exception" section. String and byte string1) py3.0 removes the Unicode type. Currently, only one type of string is available, but it is almost the same as the Unicode of version 2.x. 2) For a byte string, see the "Data Type" section 2nd. Data Type1) py3.0 removes the long type, and now there is only one integer -- int, but its behavior is like the long of the 2.x version. 2) added the bytes type, corresponding to 2. the method for defining a bytes literal value for the eight-Bit String of Version X is as follows: >>> B = B 'China' >>> type (B) <type 'bytes '> STR object and bytes object can be used. encode () (STR-> bytes) or. the decode () (bytes-> Str) method converts each other. >>> S = B. decode () >>>> s 'China' >>> b1 = S. encode () >>> B1b 'China' 3) of dict. keys (),. items and. the values () method returns the iterator, and the previous iterkeys () and other functions are discarded. Dict. has_key () is also removed. Replace it with in. Object-oriented1) 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) Explain quencesetsizedvaluesview _ all ____ builtins ____ Doc ____ file ____ name ___ abcoll_itemgetter_sysdefadicdictdeque 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 _ () of the iterator __() method 4) added two decorator: @ abstractmethod and @ abstractproperty, which makes it easier to compile Abstract METHODS (attributes. Exception1) 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 and 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: # note the as print (STR (error) error5 exception chain, this is because _ context _ has not been implemented in version 3.0a1. 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) if 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 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 <type 'file'> In py3.0 >>> filetraceback (most recent call last ): file "<pyshell #120>", line 1, in <module> filenameerror: Name 'file' is not defined FeelingsPython 3.0 is a revolutionary upgrade of Python. It abolished many previous features and introduced new features (such as the idea of using a large number of iterators ). It takes a lot of money for developers to upgrade from 2.x to version 3.0, not only to re-train their rigid fingers, but also to let their brains jump out of the previous rules. Now, only the alpha 1 version has been released, and many other features have not been implemented. According to the pep 3000 plan, all new features will be implemented by next April, so we will have a stronger sense of regret, right? ReferencePython 3.0 documentation

Related Article

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.