這篇文章主要介紹了Python模塊future用法原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
計算機(jī)的知識太多了,很多東西就是一個使用過程中詳細(xì)積累的過程。最近遇到了一個很久關(guān)于future的問題,踩了坑,這里就做個筆記,免得后續(xù)再犯類似錯誤。
future的作用:把下一個新版本的特性導(dǎo)入到當(dāng)前版本,于是我們就可以在當(dāng)前版本中測試一些新版本的特性。說的通俗一點,就是你不用更新python的版本,直接加這個模塊,就可以使用python新版本的功能。 下面我們用幾個例子來說明它的用法:
python 2.x print不是一個函數(shù),不能使用help. python3.x print是一個函數(shù),可以使用help.這個時候,就可以看一下future的好處了:
代碼:
1
2
3
4
5
6
|
# python2 # from __future__ import absolute_import, division, print_function #print(3/5) #print(3.0/5) #print(3//5) help ( print ) |
運(yùn)行結(jié)果:
1
2
3
4
5
|
? future git:(master) ? python future.py File "future.py", line 8 help(print) ^ SyntaxError: invalid syntax |
報錯了,原因就是python2 不支持這個語法。
上面只需要把第二行的注釋打開:
1
2
3
4
5
6
|
# python2 from __future__ import absolute_import, division, print_function #print(3/5) #print(3.0/5) #print(3//5) help ( print ) |
結(jié)果如下,就對了:
1
2
3
4
5
6
7
8
9
10
|
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. |
另外一個例子:是關(guān)于除法的:
1
2
3
4
5
6
7
|
# python2 #from __future__ import absolute_import, division, print_function print ( 3 / 5 ) print ( 3.0 / 5 ) print ( 3 / / 5 ) #help(print) |
結(jié)果:
1
2
|
? future git:(master) ? python future.py 0.6 |
把編譯宏打開,運(yùn)算結(jié)果:
1
2
3
|
? future git:(master) ? python future.py 0.6 0.6 |
看看,python3.x的語法可以使用了。
有了這兩個例子,估計你對future的用法就清晰了吧。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/dylancao/p/11904524.html