计算机的知识太多了,不少东西就是一个使用过程当中详细积累的过程。最近遇到了一个好久关于future的问题,踩了坑,这里就作个笔记,省得后续再犯相似错误。python
future的做用:把下一个新版本的特性导入到当前版本,因而咱们就能够在当前版本中测试一些新版本的特性。说的通俗一点,就是你不用更新python的版本,直接加这个模块,就能够使用python新版本的功能。 下面咱们用几个例子来讲明它的用法:git
python 2.x print不是一个函数,不能使用help. python3.x print是一个函数,能够使用help.这个时候,就能够看一下future的好处了:python3.x
代码:app
# python2 #from __future__ import absolute_import, division, print_function #print(3/5) #print(3.0/5) #print(3//5) help(print)
运行结果:函数
➜ future git:(master) ✗ python future.py File "future.py", line 8 help(print) ^ SyntaxError: invalid syntax
报错了,缘由就是python2 不支持这个语法。测试
上面只须要把第二行的注释打开:ui
1 # python2 2 from __future__ import absolute_import, division, print_function 3 4 5 #print(3/5) 6 #print(3.0/5) 7 #print(3//5) 8 help(print)
结果以下,就对了:spa
Help on built-in function print in module __builtin__: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline.
另一个例子:是关于除法的:code
# python2 #from __future__ import absolute_import, division, print_function print(3/5) print(3.0/5) print(3//5) #help(print)
结果:blog
➜ future git:(master) ✗ python future.py 0 0.6 0
把编译宏打开,运算结果:
➜ future git:(master) ✗ python future.py 0.6 0.6 0
看看,python3.x的语法能够使用了。
有了这两个例子,估计你对future的用法就清晰了吧。