Difference between python3.x and 2.x, and between python3.x2. x

Source: Internet
Author: User
Tags integer division

Difference between python3.x and 2.x, and between python3.x2. x

1. Performance
Py3.0 runs pystone benchmark 30% slower than Py2.5. Guido believes that Py3.0 has a huge space for optimization, which can be used for string and integer operations.
To achieve good optimization results.
Py3.1 performance is 15% slower than Py2.5, and there is still much room for improvement.

2. Encoding
The Py3.X source code file uses UTF-8 encoding by default, which makes the following code Legal:
>>> China = 'China'
>>> Print (China)
China

3. Syntax
1) Remove <>, switch to all! =
2) Remove ''and use repr () instead ()
3) Add the as and with keywords, and add True, False, None
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.

For example:
2. X: print "The answer is", 2*2
3. X: print ("The answer is", 2*2)
2. X: print x, # use a comma to end the line break.
3. X: print (x, end = "") # Use spaces to replace line breaks
2. X: print # output New Line
3. X: print () # output a 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) # unlike print (x, y )!
7) changes the behavior of sequence operators. For example, if x <y does not match the y type, a TypeError is thrown instead of returning the immediate bool value.
8) the input function is changed. raw_input is deleted and replaced by input:
2. X: guess = int (raw_input ('enter an integer: ') # How to read keyboard input
3. X: guess = int (input ('enter an integer: ') 9) Remove the tuples from the package. You cannot define a function like def (a, (B, c): pass.
10) the new octal variable modifies the oct () function accordingly.

The method of 2.x is as follows:
>>> 0666
438
>>> Oct (438)
'123'
3. X:
>>> 0666
SyntaxError: invalid token (<pyshell #63>, line 1)
>>> 0o666
438
>>> Oct (438)
'0o666'

11) added the binary literal and bin () functions.
>>> Bin( 438)
'0b110110110'
>>> _ 438 = '0b110110110'
>>> _ 438
'0b110110110'
12) scalable and iterative unpacking. In Py3.X, a, B, * rest = seq and * rest, a = seq are both valid and only two points are required: rest is list
Objects and seq can be iterated.
13) the new super () can no longer pass parameters to super,
>>> Class C (object ):
Def _ init _ (self, ):
Print ('C',)
>>> Class D (C ):
Def _ init (self, ):
Super (). _ init _ (a) # super () called without Parameters ()
>>> D (8)
C 8
<__ Main _. D object at 0x00D7ED90>

14) New metaclass Syntax:
Class Foo (* bases, ** kwds ):
Pass
15) supports class decorator. The usage is the same as that of the decorator function:
>>> 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 tricks of the CAPTCHA. For more information, see PEP 3129.

4. String and byte string
1) currently, only one type of string is available, but it is almost the same as unicode in 2.x. 2) For a byte string, see the 2nd entries in "data type ".
5. Data Type
1) Py3.X removes the long type, and now there is only one integer -- int, But it acts like the long type
2) The bytes type is added, which corresponds to the 8-Bit String Of The 2.x version. The following describes how to define a bytes literal:
>>> B = B 'China'
>>> Type (B)
<Type 'bytes '>
The str object and bytes object can be converted using the. encode () (str-> bytes) or. decode () (bytes-> str) method.
>>> S = B. decode ()
>>> S
'China'
>>> B1 = s. encode ()
>>> B1
B 'china'
3) dict's. keys (),. items, and. values () Methods return to the iterator, while previous iterkeys () and other functions are discarded. Also removed
Dict. has_key (), replace it with in.

6. Object-oriented
1) 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 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, 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 _ () method of the iterator.
4) added two decorator: @ abstractmethod and @ abstractproperty, which makes it easier to compile Abstract METHODS (attributes.
7. Exceptions
1) 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. 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: # Pay attention to this
Print (str (error ))
Error
5) exception chain, because _ context _ is not implemented in version 3.0a1

8. module changes
1) The cPickle module is removed and can be replaced by the pickle module. In the end, we will have a transparent and efficient module.
2) removed the imageop module.
3) removed audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2,
Rexec, sets, sha, stringold, strop, sunaudiodev, timing, and xmllib modules
4) removed the bsddb module (released separately, available at http://www.jcea.es/programacion/pybsddb.htm)
5) removed the new module.
6) The OS. tmpnam () and OS. tmpfile () functions are moved to the tmpfile module.
7) The tokenize module now uses bytes to work. The main entry point is not generate_tokens, but tokenize. tokenize ()

9. 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. Apply (), callable (), coerce (), execfile (), reduce (), and reload
() All functions are excluded

Now you can use hasattr () to replace the syntax of callable (). hasattr (), such as hasattr (string, '_ name __')

4) 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 exception 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 _ call
7) the file class is discarded. 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' 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.