ITeye博客

Python Closure

fairy_xzc · 2016-10-13 16:15 · Python · 编程语言 · Markdown

原创转载请注明出处:http://agilestyle.iteye.com/blog/2330379

 

先实现一个可变参数的求和——直接反回求和的结果

def calc_sum(*args):
    s = 0
    for n in args:
        s = s + n
    return s


# 15
print(calc_sum(1, 2, 3, 4, 5))

 

改进一下,如果不需要立刻求和,后面根据需要再进行计算求和——返回求和的函数

def lazy_sum(*args):
    def total():
        s = 0
        for n in args:
            s = s + n
        return s

    return total


f = lazy_sum(1, 2, 3, 4, 5)
print(f)
# 15
print(f())

f1 = lazy_sum(1, 2, 3, 4, 5)
f2 = lazy_sum(1, 2, 3, 4, 5)
print(f1)
print(f2)
# False
print(f1 == f2)

Console Output

Note:

内部函数total可以引用外部函数lazy_sum的参数和局部变量,这种就称为闭包(Closure)

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。