---
title: "Python Closure"
author: "fairy_xzc"
date: "2016-10-13T16:15:08Z"
tags: []
categories: ["编程语言"]
slug: "python-closure"
draft: false
lastmod: "2016-10-14T09:21:49Z"
id: 2330379
url: "https://agilestyle.iteye.com/blog/2330379"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2330379](/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

![](http://dl2.iteye.com/upload/attachment/0120/5954/5897de27-398c-3fed-821b-7acfa6e010e1.png)

Note：

内部函数total可以引用外部函数lazy\_sum的参数和局部变量，这种就称为**闭包（Closure）**