计算机的知识太多了,很多东西就是一个使用过程中详细积累的过程。最近遇到了一个很久关于future的问题,踩了坑,这里就做个笔记,免得后续再犯类似错误。

  future的作用:把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。说的通俗一点,就是你不用更新python的版本,直接加这个模块,就可以使用python新版本的功能。 下面我们用几个例子来说明它的用法:

python 2.x print不是一个函数,不能使用help. python3.x print是一个函数,可以使用help.这个时候,就可以看一下future的好处了:

  代码:

  1. # python2
  2. from __future__ import absolute_import, division, print_function
  3. #print(3/5)
  4. #print(3.0/5)
  5. #print(3//5)
  6. help(print)

  运行结果:

  1. future git:(master) python future.py
  2. File "future.py", line 8
  3. help(print)
  4. ^
  5. SyntaxError: invalid syntax

  报错了,原因就是python2 不支持这个语法。

  上面只需要把第二行的注释打开:

  1. 1 # python2
  2. 2 from __future__ import absolute_import, division, print_function
  3. 3
  4. 4
  5. 5 #print(3/5)
  6. 6 #print(3.0/5)
  7. 7 #print(3//5)
  8. 8 help(print)

  结果如下,就对了:

  1. Help on built-in function print in module __builtin__:
  2. print(...)
  3. print(value, ..., sep=' ', end='\n', file=sys.stdout)
  4. Prints the values to a stream, or to sys.stdout by default.
  5. Optional keyword arguments:
  6. file: a file-like object (stream); defaults to the current sys.stdout.
  7. sep: string inserted between values, default a space.
  8. end: string appended after the last value, default a newline.

  另外一个例子:是关于除法的:

  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)

  结果:

  1. future git:(master) python future.py
  2. 0
  3. 0.6
  4. 0

  把编译宏打开,运算结果:

  1. future git:(master) python future.py
  2. 0.6
  3. 0.6
  4. 0

 看看,python3.x的语法可以使用了。

 有了这两个例子,估计你对future的用法就清晰了吧。

 

版权声明:本文为dylancao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/dylancao/p/11904524.html