Python模块之 __future__ 转载

转载自https://www.cnblogs.com/bluescorpio/archive/2009/09/09/1563634.htmlhtml

今天在学习Python Cookbook的时候,发现一句语法from __future__ import division,很奇怪__future__这个名字,网上搜了一下,原来是颇有用的一个模块。python

详细说明见这里。按照官方的解释,至少确保在2.1以前版本的Python能够正常运行一些新的语言特性,须要使用语句 'from __future__ import *'。举例来讲:

# Enable nested scopes in Python 2.1
from __future__ import nested_scopes

若是使用这个语句,则该语句必须是模块或程序的第一个语句。此外,'__ future__' 模块中存在的特性最终将成为Python语言标准的一部分。到那时,将再也不须要使用 '__future__' 模块。

更多示例:

1. Python 2.6中也有一个 __future__ import 使得全部的字符串文本成为Unicode字符串。这就意味着\u转义序列能够用于包含Unicode字符。

from __future__ import unicode_literals

s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
'\u3081\u3000\u751f\u305f\u307e\u3054')
print len(s) # 12 Unicode characters

2. Python 2.6能够经过 import __future__ 来将print从语言语法中移除,让你能够使用函数的形式。例如:

from __future__ import print_function
print('# of entries', len(dictionary), file=sys.stderr)

3. 整数除法

python 2.5中:23/6 # 得3
from __future__ import division 以后:
23/6 # 得 3.8333333333333335函数

相关文章
相关标签/搜索