Python的未来 future模块

来源:互联网 发布:mac 美服lol下载教程 编辑:程序博客网 时间:2024/05/20 18:19

转载:http://omencathay.itpub.net/post/30163/414347


简单介绍一下python未来将会支持的一些语言特点 ,虽然Ibm的网站上也有介绍.但是太凌乱了.而且中翻译过后,代码的格式想狗屎一样.

下面简单介绍一下这些特点

nested_scopes: 改变名空间的搜索过程

generators:使用生成器.能够产生能保存当前状态的函数.

division:精确的除法

absolute_import:包含绝对路径.方便include

with_statement:安全的打开文件

想使用这写语言特点, 在文件开头加一句

from __future__ import FeatureName

比如

from __future__ import division

就能用了

下面介绍一下他们

nested_scopes: 改变使用lambda时名空间的搜索过程,按照dive into python中的话说

generators:使用生成器.能够产生能保存当前状态的函数.

注意generator使用yield返回.不是return

下面的generator每次调用都会返回字母表中下一个字母,从a开始,到z结束.

from __future__ import generators

def alphabet():
 n=0
 while n<26:
 char=chr(ord('a')+n)
 n+=1
 yield char #在这里返回,下次调用时从这里开始

调用方法

gen=alphabet()
for char in gen:
 print char

或者使用gen.next()函数.可以看到,函数内部控制变量n的值被保留下来了

在2.5中generator功能更加丰富,yield可以作为表达式的以部分,使用send方法来改变其的返回时的状态.

具体http://blog.donews.com/limodou/archive/2006/09/04/1028747.aspx

当遍历所有变量以后会引发StopIteration异常

division:精确的除法,同义

>>> 22/7
3
>>> from __future__ import division
>>> 22/7
3.1428571428571428

absolute_import:包含绝对路径.方便include

很多时候当我们要include上一层目录的文件时,不得不手动使用os来把上层目录加入搜索path.否则include就会找不到文件.使用了这个特性后.绝对路径自动加入了.可以使用绝对路径来

下面是从一封邮件里面摘录的

>> work>> |>> |- foo.py # print "foo not in bar">> |>> `- bar>> |>> |- __init__.py>> |>> |- foo.py # print "foo in bar">> |>> |- absolute.py # from __futer__ import absolute_import>> | # import foo>> |>> `- relative.py # import foo>>>>>>* Where "work" is in the path.>>>>>> (1)>>>> C:work>python -c "import bar.absolute">> foo not in bar>>>> C:work>python -c "import bar.relative">> foo in bar>>>>

with_statement:安全的打开文件

使用with open("file name ") as xx打开文件.这样不用close文件了.python会自动帮我们做这件事.

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1764543