• Index

Reads: 142923

### 函数作为返回值

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

``````def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
``````

``````>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function sum at 0x10452f668>
``````

``````>>> f()
25
``````

``````>>> f1 = lazy_sum(1, 3, 5, 7, 9)
>>> f2 = lazy_sum(1, 3, 5, 7, 9)
>>> f1==f2
False
``````

`f1()``f2()`的调用结果互不影响。

### 闭包

``````def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs

f1, f2, f3 = count()
``````

``````>>> f1()
9
>>> f2()
9
>>> f3()
9
``````

``````>>> def count():
...     fs = []
...     for i in range(1, 4):
...         def f(j):
...             def g():
...                 return j*j
...             return g
...         fs.append(f(i))
...     return fs
...
>>> f1, f2, f3 = count()
>>> f1()
1
>>> f2()
4
>>> f3()
9
``````

### Make a Comment

• Index

WARNING: You are using an old browser that does not support HTML5. Please choose a modern browser (Chrome / Firefox / Sarafi) to get a good experience.