码迷,mamicode.com
首页 > 编程语言 > 详细

Python -- 闭包

时间:2015-10-21 22:40:27      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

概念

  返回内部函数,而且内部函数和外部函数的局部变量绑定在一起

 


实例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())

 

Python -- 闭包

标签:

原文地址:http://www.cnblogs.com/roronoa-sqd/p/4899112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!