>>> myiterable=[x*x for x in range(3)] >>> for i in myiterable: print i 0 1 4 >>> for i in myiterable: print i 0 1 4 >>> mygenerator = (x*x for x in range(3)) >>> for i in mygenerator: print i 0 1 4 >>> for i in mygenerator: print i #null >>> myiterable [0, 1, 4] >>> mygenerator <generator object <genexpr> at 0x0000000002F60360>
deffunc(name="admin"): deftest(): return"now in test function" defmodify(): return"now in modify function" if name=="admin": print test() else: print modify() func()# now in test function modify()# NameError: name 'modify' is not defined # 可以看到,在func()调用时,里面的test(),modify()都会被调用 # 并且外部不可访问func内部的函数
接着,python中还可以在函数中返回函数:
1 2 3 4 5 6 7 8 9 10 11
deffunc(name="admin"): deftest(): return"now in test function" defmodify(): return"now in modify function" if name=="admin": return test else: return modify print func()#<function test at 0x0000000002AD8DD8> # 我们还可以输入func()()打印now in test function
装饰器:方便函数与类的重用,避免重复
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defdecorate_name(func): defdecorated(): print"Before execute func()" func() print"After excute func()" return decorated deffunc(): print"func() is excuting" #下面个两步骤是用@运行时如何使用的 func = decorate_name(func) func() #output: # Before execute func() # func() is excuting # After excute func()
装饰器一般用@xxx来表示,上面代码描述了我们使用后@时,代码运行的过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
from functools import wraps defdecorate_name(func): @wraps(func) defdecorated(*args,**kwargs): ifnot case: return"func not run" else: return func() return decorated
@decorate_name deffunc(): return"func is running" case = False print func()
@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能
之前讲的是函数装饰器,初次之外还有一个类装饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
from functools import wraps classMyclass(object): def__init__(self,case): self.case = case