概念
返回内部函数,而且内部函数和外部函数的局部变量绑定在一起
实例1
def make_adder(addend):
def adder(augend):
return augend + addend
return adder
p = make_adder(23)
q = make_adder(44)
print p(100)
print q(100)
实例2
def hellocounter (name): count=0 def counter(): nonlocal count count+=1 print("Hello, %s, %d access!" % (name, count)) return counter hello = hellocounter('zoro') hello() hello() hello()
实例3
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print(hello())