from __future__ import 的作用


概括:这行代码的作用是为了在低版本 python 中使用高版本特性而引入的, 在 python2 中调用 python3 中的特性,例如 print_function 实现在 2.x 中使用 3.x 中的 print() 命令。

1、absolute_import

from __future__ import absolute_import

这是一个在 py2.x 中导入 3.x 的导入特性的语句, 是为了区分出绝对导入和相对导入
声明为绝对引用。

Python 2.4 或之前默认是相对引用,即先在本目录下寻找模块。但是如果本目录中有模块名与系统 (sys.path) 模块同名冲突,而想要引用的是系统模块时,该声明就能够起作用了。

详见:https://blog.csdn.net/happyjacob/article/details/109348379

2、division

from __future__ import division

在 python3 中默认是精确除法,和数学中除法概念时一样的,而 python2 中默认的是整除,如果在 python2 想要使用精确除法,就使用这个语句来声明。

>>> 3/4
0
>>> from __future__ import division
>>> 3/4
0.75

3、print_function

from __future__ import print_function

在 python2 中使用 python3 的 print 函数

>>> print("a")
a
>>> print "a"
a
>>>
>>> from __future__ import print_function
>>> print("a")
a
>>> print "a"
  File "<stdin>", line 1
    print "a"
            ^
SyntaxError: invalid syntax

print2 支持 print “a” 和 print(“a”) 的写法,print3 只支持 print(“a”) 的写法,使用 from __future__ import print_function 后 python2 只能 print(“a”) 这种写法了

猜你喜欢

转载自blog.csdn.net/happyjacob/article/details/109396117
今日推荐