generators:使用生成器.能够产生能保存当前状态的函数.
注意generator使用yield返回.不是return
下面的generator每次调用都会返回字母表中下一个字母,从a开始,到z结束.
from__future__importgenerators
defalphabet():
n=0
whilen<26:
char=chr(ord('a')+n)
n+=1yieldchar#在这里返回,下次调用时从这里开始
调用方法
gen=alphabet()
forcharingen:
printchar
或者使用gen.next()函数.可以看到,函数内部控制变量n的值被保留下来了
在2.5中generator功能更加丰富,yield可以作为表达式的以部分,使用send方法来改变其的返回时的状态.
当遍历所有变量以后会引发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会自动帮我们做这件事.