python的import __future__作用

来源:互联网 发布:烟灶套装 知乎 编辑:程序博客网 时间:2024/06/05 17:28
  • 这是 python 2 的概念,显然 python 3 对于 python2 就是 future了
  • 该句必须放在文件的头部
Python编程语言中有很多比较有用的模块,这些模块在实际使用中可以帮助我们轻松的完成许多功能需求。我们今天将会在这里通过对Python future模块的了解,来对这方面的知识做一个详细的了解。


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


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


# Enable nested scopes in Python 2.1  
from __future__ import nested_scopes 
如果使用这个语句,则该语句必须是模块或程序的第一个语句。此外,'__ future__' 模块中存在的特性最终将成为Python语言标准的一部分。到那时,将不再需要使用Python 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 
以上就是我们对Python future模块的相关介绍。

from __future__ import print_function

指定 file 关键字参数,打印到文件流当然也可以是标准输入输出流

from __future__ import print_functionimport sysprint('error happens!', file=sys.stderr)


1. TensorFlow入门基本教程

http://edu.csdn.net/course/detail/4369

2. C++标准模板库从入门到精通 

http://edu.csdn.net/course/detail/3324

3.跟老菜鸟学C++

http://edu.csdn.net/course/detail/2901

4. 跟老菜鸟学python

http://edu.csdn.net/course/detail/2592

5. 在VC2015里学会使用tinyxml库

http://edu.csdn.net/course/detail/2590

6. 在Windows下SVN的版本管理与实战 

 http://edu.csdn.net/course/detail/2579

7.Visual Studio 2015开发C++程序的基本使用 

http://edu.csdn.net/course/detail/2570

8.在VC2015里使用protobuf协议

http://edu.csdn.net/course/detail/2582

9.在VC2015里学会使用MySQL数据库

http://edu.csdn.net/course/detail/2672





0 0
原创粉丝点击