1.__feature__模块的作用:
Python 提供了 __future__
模块,把下一个新版本的特性导入到当前版本,
这样,我们就可以在当前版本中测试一些新版本的特性。
Python 为了确保你能顺利过渡到新版本,特别提供了 __future__
模块,让你在旧的版本中试验新版本的一些特性。
一般有:
from __future__ import division, print_function, absolute_import
如果你的python版本是python2.X,你也可以按照python3.X那样使用这些函数;
2.__feature__模块功能:
python 2.7.14的__future基本上是python3中的特性,可导入的功能如下:
3.from __future__ import division
division== 新的除法特性,本来的除号/
对于分子分母是整数的情况会取整,但新特性中在此情况下的除法不会取整,取整的使用//
。
如下可见,只有分子分母都是整数时结果不同。
In [1]: 3 / 5
Out[1]: 0
In [2]: 3 // 5
Out[2]: 0
In [3]: 3.0 / 5.0
Out[3]: 0.6
In [4]: 3.0 // 5.0
Out[4]: 0.0
In [5]: from __future__ import division
In [6]: 3 / 5
Out[6]: 0.6
In [7]: 3 // 5
Out[7]: 0
In [8]: 3.0 / 5.0
Out[8]: 0.6
In [9]: 3.0 // 5.0
Out[9]: 0.0
4.from __future__ import print_function
print_function== 新的print是一个函数,如果导入此特性,之前的print语句就不能用了。在python2.x中print函数无需括号,但在python3.x中需要括号;在代码中导入print_function后,再写print必须加括号。
5.from __future__ import unicode_literals
unicode_literals== 这个是对字符串使用unicode字符。
In [1]: print '目录'
鐩綍
In [2]: from __future__ import unicode_literals
In [3]: print '目录'
目录
6.from __future__ import absolute_import
absolute_import== 绝对导入, 这个语句的意思是加入绝对引用的特征;
直白的意思是,比如:
在你的包pkg中有这样的结构:
pkg/
pkg/striing.py
pkg/main.py
假如你在main.py中想要引用string.py则应写入import string
but 这种写法引用的是pkg/string.py;这个string即引用的是相同目录下的string
如果:我要引用的是Python系统自带的标准的string,那么我的这个引用则是错误的,因为路径为相对引用,引用的是pkg/string
解决方法:加入 from __future__ import absolute_import;
7.from __future__ import nested_scopes
nested_scopes== 这个是修改嵌套函数或lambda函数中变量的搜索顺序,
从当前函数命名空间->模块命名空间
的顺序更改为了当前函数命名空间->父函数命名空间->模块命名空间
,
python2.7中默认使用
8. from __future__ import nested_scopes
generators== 生成器,对应yield的语法,python2.7中默认使用
9.with_statement 是使用with关键字,python2.7是默认使用
10.作用:python2和python3的兼容性:
重要的功能是基本用以下几句就可以让python2和python3有良好的兼容性了.
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
参考:
1.https://blog.youkuaiyun.com/Allenlzcoder/article/details/93901615