python的模塊future用法實例解析


  計算機的知識太多了,很多東西就是一個使用過程中詳細積累的過程。最近遇到了一個很久關於future的問題,踩了坑,這里就做個筆記,免得后續再犯類似錯誤。

  future的作用:把下一個新版本的特性導入到當前版本,於是我們就可以在當前版本中測試一些新版本的特性。說的通俗一點,就是你不用更新python的版本,直接加這個模塊,就可以使用python新版本的功能。 下面我們用幾個例子來說明它的用法:

python 2.x print不是一個函數,不能使用help. python3.x print是一個函數,可以使用help.這個時候,就可以看一下future的好處了:

  代碼:

# 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 不支持這個語法。

  上面只需要把第二行的注釋打開:

  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)

  結果如下,就對了:

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.

  另外一個例子:是關於除法的:

# 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
0
0.6
0

  把編譯宏打開,運算結果:

➜  future git:(master) ✗ python future.py
0.6
0.6
0

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

 有了這兩個例子,估計你對future的用法就清晰了吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM