当前位置: 移动技术网 > IT编程>脚本编程>Python > Python2和Python3的区别详解

Python2和Python3的区别详解

2018年03月22日  | 移动技术网IT编程  | 我要评论

北京大中电器网上商城,双面女友下载,超级保镖 迅雷下载

1.统一了字符编码支持。Python2 的默认编码是 asscii,这也是导致 Python2 中经常遇到编码问题的原因之一,至于是为什么会使用 asscii 作为默认编码,原因在于 Python这门语言诞生的时候还没出现 Unicode。Python 3 默认采用了 UTF-8 作为默认编码,因此你不再需要在文件顶部写 # coding=utf-8 了。在 Python2 中,字符串有两个类型,一个是 unicode,一个是 str,前者表示文本字符串,后者表示字节序列,不过两者并没有明显的界限,开发者也感觉很混乱,不明白编码错误的原因,不过在 Python3 中两者做了严格区分,分别用 str 表示字符串,byte 表示字节序列,任何需要写入文本或者网络传输的数据都只接收字节序列,这就从源头上阻止了编码错误的问题。

2.The print statement has been replaced with a print() function,the same change is applied to exec statement。

3.修改了一些语法,map、filter以及dict的items/keys/values方法返回迭代对象而不是列表,描述符协议,保存类属性定义顺序,保存关键字参数顺序

4.xrange重命名为range同时更改的还有一系列内置函数及方法, 都返回迭代器对象, 而不是列表或者 元组, 比如 filter, map, dict.items 等;不再有经典类

5.增加一些新的模块。concurrent.futures、venv、unittest.mock、asyncio、selectors、typing等

6.修改了一些模块。主要是对模块添加函数/类/方法(如functools.lru_cache、threading.Barrier)或者参数。

7.模块改名。把一些相关的模块放进同一个包里面(如httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib放进了http里面,urllib, urllib2, urlparse, robotparse放进了urllib里面),个例如SocketServer改成了socketserver,Queue改成queue等

8 去掉了一些模块或者函数。gopherlib、md5、contextlib.nested、inspect.getmoduleinfo等。去掉的内容的原因主要是2点:1. 过时的技术产物,已经没什么人在用了;2. 出现了新的替代产物后者被证明存在意义不大。

9.优化。重新实现了dict可以减少20%-25%的内存使用;提升pickle序列化和反序列化的效率;collections.OrderedDict改用C实现;通过os.scandir对glob模块中的glob()及iglob()进行优化,使得它们现在大概快了3-6倍等.. 这些都是喜大普奔的好消息,同样开发者不需要感知,默默的就会让结果变得更好。

10.nonlocal;我们都知道在Python2中可以在函数里面可以用关键字 global 声明某个变量为全局变量,但是在嵌套函数中,想要给一个变量声明为非局部变量是没法实现的,在Pyhon3,新增了关键字 nonlcoal,使得非局部变量成为可能。

11.python3 彻底废弃了 long+int 双整数实现的方法, 统一为 int , 支持高精度整数运算.

12.except Exception, e变成except (Exception) as e只有 python2.5 及以下版本不支持该语法. python2.6 是支持的. 不算新东西

13.New Metaclass Syntax. Instead of:

class C:
    __metaclass__ = M
    ...
#you must now use:

class C(metaclass=M):
    ...

14.New super(). You can now invoke super() without arguments and (assuming this is in a regular instance method defined inside a class statement) the right class and instance will automatically be chosen. With arguments, the behavior of super() is unchanged.

15.raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

16.A new built-in function next() was added to call the __next__() method on an object.

17.The round() function rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result instead of away from zero. (For example, round(2.5) now returns 2 rather than 3.) round(x[, n]) now delegates to x.round([n]) instead of always returning a float. It generally returns an integer when called with a single argument and a value of the same type as x when called with two arguments.

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网