Liuxingyuan class talks about the difference between Python2 and Python3, novices quickly come over!

thumbnail

In the process of learning Python, many new students will hesitate whether to learn Python2 or Python3. The editor will sort out the differences between Python2 and Python3 for you. Let’s take a look. I hope it will be helpful to the confused students~

  1. Performance

Py3.0 runs the pystone benchmark 30% slower than Py2.5. Guido believes that Py3.0 has great optimization space, and can achieve good optimization results in string and integer operations. The performance of Py3.1 is 15% slower than that of Py2.5, and there is still a lot of room for improvement.

  1. Coding

Py3.X source files use utf-8 encoding by default

  1. Grammar
  1. Removed <>, all use !=

  2. Remove `` and use repr() instead

  3. Keywords are added as and with, as well as True, False, None

  4. Integer division returns a floating point number, to get an integer result, use //

  5. Add nonlocal statement. Outer (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. The same is true for the exec statement, which has been changed to the exec() function

  7. Changed the behavior of ordering operators, e.g. x<y, throws TypeError when the types of x and y do not match instead of returning a random bool value

  8. The input function was changed, raw_input was removed and replaced with input:

2.X:guess = int(raw_input('Enter an integer : ')) # Method to read keyboard input

3.X:guess = int(input('Enter an integer : '))

  1. Remove tuple parameter unpacking. Can't def(a, (b, c)):pass define functions like this

  2. New-style octal word variable, modify the oct() function accordingly.

  3. Added binary literal and bin() function

  4. Extended iterable unpacking. In Py3.X, a, b, *rest = seq and *rest, a = seq are all legal, only two things are required: rest is a list, and objects and seq are iterables.

  5. The new super() can no longer pass parameters to super(),

  6. New metaclass syntax:

class Foo(*bases, **kwds):

pass

  1. Support class decorator. The usage is the same as the function decorator:
  1. 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 byte strings, see entry 2 of "Data Types"

  1. Data Types
  1. Py3.X removed the long type, and now there is only one integer type - int, but it behaves like the 2.X version of long

  2. Added the bytes type, which corresponds to the 2.X version of the octet string. The method to define a bytes literal is as follows:

str objects and bytes objects can be converted to each other using the .encode() (str -> bytes) or .decode() (bytes ->str) methods.

  1. The .keys(), .items and .values() methods of dict return iterators, and the previous functions such as iterkeys() are discarded. Also removed is dict.has_key(), replace it with in
  1. Object Oriented
  1. Introduce abstract base classes (Abstraact Base Classes, ABCs).

  2. Container classes and iterator classes are ABCsized.

  3. The next() method of the iterator is renamed to next(), and the built-in function next() is added to call the next() method of the iterator

  4. Added two decorators, @abstractmethod and @abstractproperty, making it more convenient to write abstract methods (properties).

  1. Exception
  1. So the exceptions all inherit from BaseException and remove StardardError

  2. Removed the sequence behavior and .message attribute of the exception class

  3. Use raise Exception(args) instead of raise Exception, args syntax

  4. The syntax for catching exceptions is changed, and the as keyword is introduced to identify exception instances

  5. Exception chain, because context is not implemented in version 3.0a1

  1. Module changes
  1. Removed cPickle module, can use pickle module instead. Eventually 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 bsddb module (released separately, available from )

  5. Removed the new module

  6. The os.tmpnam() and os.tmpfile() functions have been moved to the tmpfile module

  7. The tokenize module now works with bytes. The main entry point is no longer generate_tokens, but tokenize.tokenize()

  1. Other
  1. xrange() is renamed to range(). To use range() to get a list, you must explicitly call:

>>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  1. The bytes object cannot be hashed, nor does it support the b.lower(), b.strip() and b.split() methods, but for the latter two you can use b.strip(b' \n\t\r \f ') and b.split(b' ') to achieve the same purpose

  2. zip(), map() and filter() all return iterators. The apply(), callable(), coerce(), execfile(), reduce() and reload() functions have been removed. Now you can use hasattr() to replace callable(). The syntax of hasattr() is: hasattr( string, 'name')

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

  4. If x < y cannot be compared, a TypeError exception is thrown. 2.x versions return pseudo-random boolean values

  5. The getslice family members are deprecated. a[i:j] is converted to a.getitem(slice(I, j)) or setitem and delitem calls depending on the context

  6. The file class is deprecated

The above is all the content shared this time. If you want to learn more Python skills, please continue to pay attention to Liuxingyuan Classroom!

Latest Programming News and Information | GeekBar

Related Posts