python观察日志(part10)--__future__ 模块

学习笔记,有错必纠


__future__模块


我们利用官方文档学习一下__future__模块:

To avoid confusing existing tools that analyze import statements and expect to find the modules they’re importing.

To ensure that future statements run under releases prior to 2.1 at least yield runtime exceptions

To document when incompatible changes were introduced, and when they will be — or were — made mandatory. This is a form of executable documentation, and can be inspected programmatically via importing __future__ and examining its contents.

所以说,如果某个版本(比如python3.5)中存在某个新的功能特性(比如精确除法),而这个特性和当前版本(比如python2.7)不兼容,也就是它在该版本中不是语言标准,那么我如果想要使用该特性的话,就需要从__future__模块中导入。


python实现


我们可以利用__future__ 模块,在python2.X中,像python3.X那样,使用加括号的print,或者使用精确除法。

以下是在python2.7.12交互模式下运行:

>>> print 'Bunny'
Bunny
>>> 3/2
1
>>> from __future__ import print_function, division
>>> print('Huang')
Huang
>>> 3/2
1.5

我们可以看到,在我们没有导入模块时,print不用加括号,导入后,python2就可以使用python3中print的特性;同样,当我们没有导入该模块时,/操作符执行的是截断除法,当我们导入后,/执行的是精确除法。

猜你喜欢

转载自blog.csdn.net/m0_37422217/article/details/106169609