Liuxingyuan class talks about the difference between Python2 and Python3, novices quickly come over!
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~
- 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.
- Coding
Py3.X source files use utf-8 encoding by default
- Grammar
Removed <>, all use !=
Remove `` and use repr() instead
Keywords are added as and with, as well as True, False, None
Integer division returns a floating point number, to get an integer result, use //
Add nonlocal statement. Outer (non-global) variables can be assigned directly using noclocal x
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
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
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 : '))
Remove tuple parameter unpacking. Can't def(a, (b, c)):pass define functions like this
New-style octal word variable, modify the oct() function accordingly.
Added binary literal and bin() function
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.
The new super() can no longer pass parameters to super(),
New metaclass syntax:
class Foo(*bases, **kwds):
pass
- Support class decorator. The usage is the same as the function decorator:
- Strings and Byte Strings
Now the string has only one type of str, but it is almost the same as the 2.x version of unicode.
For byte strings, see entry 2 of "Data Types"
- Data Types
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
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.
- 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
- Object Oriented
Introduce abstract base classes (Abstraact Base Classes, ABCs).
Container classes and iterator classes are ABCsized.
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
Added two decorators, @abstractmethod and @abstractproperty, making it more convenient to write abstract methods (properties).
- Exception
So the exceptions all inherit from BaseException and remove StardardError
Removed the sequence behavior and .message attribute of the exception class
Use raise Exception(args) instead of raise Exception, args syntax
The syntax for catching exceptions is changed, and the as keyword is introduced to identify exception instances
Exception chain, because context is not implemented in version 3.0a1
- Module changes
Removed cPickle module, can use pickle module instead. Eventually we will have a transparent and efficient module.
Removed the imageop module
Removed audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter,mimify, popen2,rexec, sets, sha, stringold, strop, sunaudiodev, timing and xmllib modules
Removed bsddb module (released separately, available from )
Removed the new module
The os.tmpnam() and os.tmpfile() functions have been moved to the tmpfile module
The tokenize module now works with bytes. The main entry point is no longer generate_tokens, but tokenize.tokenize()
- Other
- 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]
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
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')
string.letters and related .lowercase and .uppercase have been removed, please use string.ascii_letters instead, etc.
If x < y cannot be compared, a TypeError exception is thrown. 2.x versions return pseudo-random boolean values
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
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